I’m trying to find all fields annotated with a custom annotation, but it doesn’t seem to detect it. The same code works fine for standard annotations, such as @Deprecated.
Minimal code to reproduce:
public class MyClass {
public @interface MyAnnotation {}
@MyAnnotation Object someObject;
@MyAnnotation @Deprecated Object someDeprecatedObject;
@Deprecated Object aThirdObject;
public static void main(String[] args) {
Class<?> cls = MyClass.class;
for (Field field : cls.getDeclaredFields()) {
System.out.print(field.getName());
for (Annotation a : field.getDeclaredAnnotations())
System.out.print(" " + a);
System.out.println();
}
}
}
Output:
someObject
someDeprecatedObject @java.lang.Deprecated()
aThirdObject @java.lang.Deprecated()
@Deprecated comes up, but @MyAnnotation doesn’t! Help!
By default, annotations are not kept at runtime and so cannot be reflected upon. You need to declare your annotation like this to ensure it exists at runtime: