@MyAnnotation
public class Foo {}
public class Foo implements MarkerInterface {} (1)
@MyAnnotation
public class Foo {} (2)
public interface MyMark {}
class MarkedClass implements MyMark {}
class NonMarkedClass {}
class Main {
public static void main(String[] args) {
MarkedClass marked = new MarkedClass();
NonMarkedClass nonMarked = new NonMarkedClass();
test(marked);
//test(nonMarked);
}
static void test(MyMark markedObject) {
System.out.println("Метод 'Test' успешно завершен!");
}
}
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(value = ElementType.TYPE)
@Retention(value = RetentionPolicy.RUNTIME)
public @interface MyAnnotation {}
public interface MyMark {}
@MyAnnotation
class Parent implements MyMark {}
class Child extends Parent {}
class Main {
public static void main(String[] args) {
Parent parent = new Parent();
Child child = new Child();
testInterface(parent);
testInterface(child);
testAnnotation(parent);
testAnnotation(child);
}
public static void testInterface(MyMark markedObject) {
System.out.println("Метод 'TestInterface' успешно завершен!");
}
public static void testAnnotation(Object object) {
if (!object.getClass().isAnnotationPresent(MyAnnotation.class)) {
throw new RuntimeException("Объект не аннотирован аннотацией 'MyAnnotation'");
}
System.out.println("Метод 'testAnnotation' успешно завершен!");
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
@Documented
public @interface MyAnnotation {
String name() default "";
int value();
}
// Оба значения приведены, их именование обязательно
@MyAnnotation(name = "какое-то имя", value = 42)
public class MyType { ... }
// Присутствует только "value()", в качестве "name()" будет его значение по умолчанию
@MyAnnotation(value = 42)
public class MyType2 { ... }
// Если требуется только "value()", мы можем опустить имя
@MyAnnotation(42)
public class MyType3 { ... }
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface JavaFileInfo {
String name() default "Igor M.";
String value() default "0.0";
}
@JavaFileInfo("2.0")
public class DemoClass {
@JavaFileInfo(name = "Chi Max", value = "1.0")
public void printString() {}
}
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
public class Main {
public static void main(String[] args) throws NoSuchMethodException, SecurityException {
Class<DemoClass> demoClassObj = DemoClass.class;
readAnnotationOn(demoClassObj);
Method method = demoClassObj.getMethod("printString");
readAnnotationOn(method);
}
static void readAnnotationOn(AnnotatedElement element) {
try {
System.out.println("\nПоиск аннотаций в " + element.getClass().getName());
Annotation[] annotations = element.getAnnotations();
for (Annotation annotation : annotations) {
if (annotation instanceof JavaFileInfo fileInfo) {
System.out.println("Автор: " + fileInfo.name());
System.out.println("Версия: " + fileInfo.value());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target
@Target(ElementType.ANNOTATION_TYPE)
public @interface MetaAnnotationType {
...
}
@Target({})
public @interface MemberType {
...
}
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.FIELD})
public @interface Bogus {
...
}
@Target({ElementType.TYPE_PARAMETER, ElementType.TYPE_USE})
@interface TypeAnnotation { ... }
void method() throws @TypeAnnotation NullPointerException {...}
@NotNull String str = getValue(args);
@Encrypted String str;
@Format(theFormatterConstant) String str;
@Localized String str;
List<@ReadOnly T> list;
Store<@NotNull Product> product;
Store<@Prod(Type.Grocery) Product> product;
void showResources(@Authenticated User user);
@SwingElementOrientation int orientation;
@Positive int i;
@CreditCard string cardNumber;
Date date = (@Readonly Date) object;
Date date = (@NotNull Date) object;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface RetentionAnnotation {}
@RetentionAnnotation
@Deprecated
public class AnnotatedClass {}
import java.lang.annotation.Annotation;
public class Main {
public static void main(String[] args) {
AnnotatedClass anAnnotatedClass = new AnnotatedClass();
Annotation[] annotations = anAnnotatedClass.getClass().getAnnotations();
System.out.println("Общее кол-во аннотаций времени исполнения (RunTime): " + annotations.length);
System.out.println("1: " + annotations[0]);
System.out.println("2: " + annotations[1]);
}
}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Documented
import java.lang.annotation.Documented;
@Documented
public @interface TestDocumented {
String doTestDocument();
}
public @interface TestNotDocumented {
String doTestNoDocument();
}
public class Tester {
@TestDocumented(doTestDocument = "Hello DOC with annotation")
public void doSomeTestDocumented() {
System.out.println("Test for annotation with 'Documented'");
}
@TestNotDocumented(doTestNoDocument = "Hello DOC without annotation")
public void doSomeTestNotDocumented() {
System.out.println("Test for annotation without 'Documented'");
}
}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Inherited
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface InheritantAnnotation {}
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface NonInheritantAnnotation {}
@InheritantAnnotation
@NonInheritantAnnotation
public class Parent {}
public class Child extends Parent {}
import java.lang.annotation.Annotation;
public class Main {
public static void main(String[] args) {
Parent parent = new Parent();
Child child = new Child();
if(parent.getClass().getAnnotations().length > 0) {
System.out.println("Для класса 'Parent' применены следующие аннотации: ");
for(Annotation annotationName: parent.getClass().getAnnotations()) {
System.out.println(annotationName);
}
} else {
System.out.println("К классу 'Parent' не применены какие-либо аннотации.");
}
if(child.getClass().getAnnotations().length > 0) {
System.out.println("\nДля класса 'Child' применены следующие аннотации: ");
for(Annotation annotationName: child.getClass().getAnnotations()) {
System.out.println(annotationName);
}
} else {
System.out.println("\nК классу 'Child' не применены какие-либо аннотации.");
}
}
}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Repeatable
@interface Game {
String name() default "Что-то под вопросом";
String day();
}
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
@interface Games {
Game[] value();
}
@Games({
@Game(name = "Крикет", day = "воскресенье"),
@Game(day = "четверг"),
@Game(name = "Хоккей", day = "понедельник")
})
public class Main {
public static void main(String[] args) {
Games games = Main.class.getAnnotation(Games.class);
for (Game game : games.value()) {
System.out.println(game.name() + " в " + game.day());
}
}
}
import java.lang.annotation.Repeatable;
@Repeatable(Games.class)
@interface Game {
String name() default "Что-то под вопросом";
String day();
}
@Game(name = "Крикет", day = "воскресенье")
@Game(day = "четверг")
@Game(name = "Хоккей", day = "понедельник")
public class Main {
public static void main(String[] args) {
Games games = Main.class.getAnnotation(Games.class);
for (Game game : games.value()) {
System.out.println(game.name() + " в " + game.day());
}
}
}
@Game(name = "Крикет", day = "воскресенье")
@Game(day = "вторник")
@Game(name = "Хоккей", day = "пятница")
public class Main {
public static void main(String[] args) {
Game[] arrayGames = Main.class.getAnnotationsByType(Game.class);
for(Game game : arrayGames) {
System.out.println(game.name() + " в " + game.day());
}
}
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override
public class Parent {
public void display() {
System.out.println("Выполнился метод из родительского класса");
}
}
public class Child extends Parent {
public void display() {
System.out.println("Выполнился метод из класса-наследника");
}
}
public class Main {
public static void main(String args[]) {
Child instance = new Child();
instance.display();
}
}
public class Child extends Parent {
public void dispay() {
System.out.println("Выполнился метод из класса-наследника");
}
}
public class Child extends Parent {
@Override
public void dispay() {
System.out.println("Выполнился метод из класса-наследника");
}
}
public class Child extends Parent {
@Override
public void display() {
System.out.println("Выполнился метод из класса-наследника");
}
}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, MODULE, PARAMETER, TYPE})
public @interface Deprecated
public class Child extends Parent {
@Override
@Deprecated(since = "1.2", forRemoval = true)
public void display() {
System.out.println("Выполнился метод из класса-наследника");
}
}
public class Main {
public static void main(String args[]) {
Child instance = new Child();
instance.display();
}
}
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE, MODULE})
@Retention(RetentionPolicy.SOURCE)
public @interface SuppressWarnings
public class Parent {
@SuppressWarnings("unused")
public void display() {
System.out.println("Выполнился метод из родительского класса");
}
}
public class Main {
@SuppressWarnings("deprecation")
public static void main(String[] args) {
Child instance = new Child();
instance.display();
}
}
@SuppressWarnings({"unused", "deprecation"})
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD})
public @interface SafeVarargs
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface FunctionalInterface
@FunctionalInterface
public interface MyFunctionalInterface {
abstract public void abstractMethod();
//abstract public void anotherAbstractMethod();
}
public class Main implements MyFunctionalInterface {
public static void main(String[] args) {
Main main = new Main();
main.abstractMethod();
}
@Override
public void abstractMethod() {
System.out.println("Это сообщение из abstractMethod()");
}
}
package functional;
@FunctionalInterface
public interface AnotherFunctionalInterface extends MyFunctionalInterface {
abstract public void anotherAbstractMethod();
}
@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.SOURCE)
public @interface Native
public final class Integer {
@Native public static final int MIN_VALUE = 0x80000000;
// последующий код опущен
}
var session = request.getHttpSession();
var object = session.getAttribute("object"); (1)
var clazz = object.getClass(); (2)
var methods = clazz.getMethods(); (3)
for (var method : methods) {
if (method.getParameterCount() == 0) { (4)
method.invoke(foo); (5)
}
}
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<annotationProcessors>
<annotationProcessor>ch.frankel.blog.SampleProcessor</annotationProcessor>
</annotationProcessors>
</configuration>
</plugin>
</plugins>
</build>
@SupportedAnnotationTypes("ch.frankel.blog.*") (1)
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class SampleProcessor extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> annotations, (2)
RoundEnvironment env) {
annotations.forEach(annotation -> { (3)
Set<? extends Element> elements = env.getElementsAnnotatedWith(annotation); (4)
elements.stream()
.filter(TypeElement.class::isInstance) (5)
.map(TypeElement.class::cast) (6)
.map(TypeElement::getQualifiedName) (7)
.map(name -> "Class " + name + " is annotated with " + annotation.getQualifiedName())
.forEach(System.out::println);
});
return true;
}
}