Reflection getAnnotations() returns null

java, reflection

Solution

I just tested this for you, and it just works:

public class StackOverflowTest {

    @Test
    public void testName() throws Exception {

        Annotation[] annotations = Obj.class.getDeclaredField("myField").getAnnotations();

        System.out.println(annotations[0]);
    }
}

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface Searchable {

}

class Obj {

    @Searchable
    String myField;
}

I ran it, and it produces the following output:

@nl.jworks.stackoverflow.Searchable()

Can you try running the above class in your IDE? I tried it with IntelliJ, openjdk-6.

Problem

Searchable.java ``` @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface Searchable { } ``` Obj.java ``` public class Obj { @Searchable String myField; } ``` void main(String[] args) ``` Annotation[] annotations = Obj.class.getDeclaredField("myField").getAnnotations(); ``` I would expect `annotations` to be containing my `@Searchable`. Though it is `null`. According to documentation, this method: Returns all annotations present on this element. (Returns an array of length zero if this element has no annotations.) The caller of this method is free to modify the returned array; it will have no effect on the arrays returned to other callers. Which is even more weird (to me), since it returns `null` instead of `Annotation[0]`. What am I doing wrong here and more important, how will I be able to get my `Annotation`?

Original source