I am trying to play with reflection and annotations.
For some reason whenever I add an annotation to a field (or a class or a method), and use reflection to look at 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.
BTW, Java does not ignore annotations in general, and when (for example) I use the @Deprecated
annotation - Eclipse recognizes it and tells me the class is deprecated.
I am using Eclipse Indigo and Java SE Development Kit 7 update 2. Thanks!
By default, annotations are not available to reflection. In order to do so, you need to change the retention policy, i.e.
@Retention(RetentionPolicy.RUNTIME)
public @interface Anno {}
The various retention policies can be found in the Javadoc. The default (for mysterious reasons that nobody seems to know) is CLASS
.
I would check the @Retention e.g.
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface Deprecated {
}
If you don't set it, it won't be visible at runtime.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With