Reflect.Field.nnotes is always null

I try to play with reflection and annotations. For some reason, when I add annotation to a field (or class or method) and use reflection to view the field, I see that its annotations field is null.

For example, this code:

 public class Test { public static void main(String[] args) throws NoSuchFieldException, SecurityException { System.out.println(Test.class.getField("bl").getAnnotations().length); } @anno public int bl; public @interface anno {} } 

prints 0.

By the way, Java does not ignore annotations at all, and when (for example) I use the @Deprecated annotation - Eclipse recognizes it and says that the class is deprecated.

I am using the Eclipse Indigo update and Java SE Development Kit 7 2. Thank you!

+6
source share
2 answers

By default, annotations are not available for reflection. To do this, you need to change the storage policy, i.e.

 @Retention(RetentionPolicy.RUNTIME) public @interface Anno {} 

Various storage policies can be found in Javadoc . By default (for mysterious reasons that no one knows about) CLASS .

+22
source

I would check @Retention, for example.

 @Documented @Retention(RetentionPolicy.RUNTIME) public @interface Deprecated { } 

If you do not install it, it will not be displayed at runtime.

+4
source

Source: https://habr.com/ru/post/910360/


All Articles