Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reflect.Field.annotations always null

Tags:

java

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!

like image 376
Ginandi Avatar asked Mar 09 '12 15:03

Ginandi


2 Answers

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.

like image 92
skaffman Avatar answered Oct 16 '22 16:10

skaffman


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.

like image 39
Peter Lawrey Avatar answered Oct 16 '22 17:10

Peter Lawrey