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
?
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 {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With