reflect.Field.annotations siempre nulo

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.

Por ejemplo, este código:

public class Test {
    public static void main(String[] args) throws NoSuchFieldException, SecurityException {
    public int bl;    

    public @interface anno {}    

impresiones 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!

preguntado el 09 de marzo de 12 a las 15:03

2 Respuestas

By default, annotations are not available to reflection. In order to do so, you need to change the retention policy, i.e.

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.

Respondido 01 ago 13, 12:08

@Ginandi: Nice of you to say so :) Someone still thought it worth a downvote, mind you... - skaffman

I would check the @Retention e.g.

public @interface Deprecated {

If you don't set it, it won't be visible at runtime.

respondido 09 mar '12, 15:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.