Reflection getAnnotations() returns null

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.


Your code is correct. The problem is somewhere else. I just copied and run your code and it works.

It is possible that you are importing the wrong Obj class in your code you may want to check that first.


In my case, i had forgotten to add

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)

to the method, so in the end it should look like:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
}