Ginandi
Ginandi

Reputation: 853

reflect.Field.annotations always null

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!

Upvotes: 6

Views: 2035

Answers (2)

skaffman
skaffman

Reputation: 403581

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.

Upvotes: 24

Peter Lawrey
Peter Lawrey

Reputation: 533870

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.

Upvotes: 5

Related Questions