John Smith
John Smith

Reputation: 1793

How to get class annotation in java?

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?

Upvotes: 47

Views: 59481

Answers (2)

Denis Zavedeev
Denis Zavedeev

Reputation: 8307

Having the default Retention of an annotation does not mean that you can not read it at run-time.

Since

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.

It is possible to access them reading the .class file directly


This can be accomplished by using the ASM library (handling some corner cases, of course).

Check out its excellent User guide. In particular section 4.2 Annotations.


You may want to refer to the Spring framework's handling of such annotations (it uses shaded asm dependency):

Upvotes: 0

Matt Ball
Matt Ball

Reputation: 360016

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 {
}

Upvotes: 56

Related Questions