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 {
}
Share:
51,941

Related videos on Youtube

John Smith
Author by

John Smith

Updated on July 09, 2022

Comments

  • John Smith
    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
      matbrgz almost 11 years
      Unless explicitly marked so an annotation is only available at compile time.
  • John Smith
    John Smith almost 11 years
    and 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
    Matt Ball almost 11 years
    Why 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.