So there is the abstract @MyAnno

 import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.FIELD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface MyAnno { String value(); } 

Why can not I access its value through the code clazz.getAnnotation(MyAnno.class) using the value() method, where Class clazz = object.getClass();

When working with class fields, everything is ok, that is, this code works field.getAnnotation(MyAnno.class).value() , where field is an element of the array
Field[] fields = clazz.getDeclaredFields()

PS clazz.isAnnotationPresent(MyAnno.class) true

  • object comes as a parameter to the function: Object object - KnockKnock
  • probably in @Target should be ElementType.METHOD - keekkenen
  • The annotation is in class. For the class, it seems like ElementType.TYPE answers. And no, it did not help - KnockKnock

1 answer 1

Suppose there is such a class:

 @MyAnno("vvv") public class Anno { @MyAnno("xxx") public final int x = 0; } 

Test code for annotation for this class:

 public static void main(String[] args) { Object object = new Anno(); Class<?> clazz = object.getClass(); Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { MyAnno myAnno = field.getAnnotation(MyAnno.class); System.out.println("Field value: " + myAnno.value()); } MyAnno myAnno = clazz.getAnnotation(MyAnno.class); System.out.println("Class value: " + myAnno.value()); } 

The screen displays:

 Field value: xxx Class value: vvv 

If use

 Class clazz = object.getClass(); 

you will have to explicitly type:

 MyAnno myAnno = (MyAnno)clazz.getAnnotation(MyAnno.class); 

Because when using raw-type ( Class ), generic types are erased in methods, which is why the getAnnotation method starts returning just Annotation .