How to get class annotation in java?
51,941
The default retention policy is RetentionPolicy.CLASS
which means that, by default, annotation information is not retained at runtime:
Annotations are to be recorded in the class file by the compiler but need not be retained by the VM at run time. This is the default behavior.
Instead, use RetentionPolicy.RUNTIME
:
Annotations are to be recorded in the class file by the compiler and retained by the VM at run time, so they may be read reflectively.
...which you specify using the @Retention
meta-annotation:
@Retention(RetentionPolicy.RUNTIME)
public @interface NewAnnotationType {
}
Related videos on Youtube
Author by
John Smith
Updated on July 09, 2022Comments
-
John Smith almost 2 years
I have created my own annotation type like this:
public @interface NewAnnotationType {}
and attached it to a class:
@NewAnnotationType public class NewClass { public void DoSomething() {} }
and I tried to get the class annotation via reflection like this :
Class newClass = NewClass.class; for (Annotation annotation : newClass.getDeclaredAnnotations()) { System.out.println(annotation.toString()); }
but it's not printing anything. What am I doing wrong?
-
matbrgz almost 11 yearsUnless explicitly marked so an annotation is only available at compile time.
-
-
John Smith almost 11 yearsand what if I want to use the annotation type from external jar? I tried to do it the same way, but it didnt work. Even the setting RetentionPolicy to SOURCE did not help. Any idea?
-
Matt Ball almost 11 yearsWhy did you think that using
RetentionPolicy.SOURCE
would make a difference? The JavaDoc explicitly says that means that "Annotations are to be discarded by the compiler." At any rate you'll need to elaborate further on the exact problematic setup; I don't see what difference using an external JAR makes. This might be best asked in a new, separate question.