Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflection getAnnotations() returns null

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?

like image 618
Menno Avatar asked May 03 '13 13:05

Menno


3 Answers

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.

like image 87
Erik Pragt Avatar answered Nov 06 '22 14:11

Erik Pragt


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.

like image 31
Adam Arold Avatar answered Nov 06 '22 15:11

Adam Arold


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 {
}
like image 1
Johannes Hinkov Avatar answered Nov 06 '22 15:11

Johannes Hinkov