Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 288
John Smith Avatar asked Jul 28 '13 13:07

John Smith


People also ask

How do you know if a class is annotated?

The isAnnotation() method is used to check whether a class object is an annotation. The isAnnotation() method has no parameters and returns a boolean value. If the return value is true , then the class object is an annotation. If the return value is false , then the class object is not an annotation.

Can classes be annotated in Java?

Annotations can be applied to declarations: declarations of classes, fields, methods, and other program elements. When used on a declaration, each annotation often appears, by convention, on its own line. As of the Java SE 8 release, annotations can also be applied to the use of types.

What is @interface annotation in Java?

Annotation is defined like a ordinary Java interface, but with an '@' preceding the interface keyword (i.e., @interface ). You can declare methods inside an annotation definition (just like declaring abstract method inside an interface). These methods are called elements instead.


1 Answers

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 { } 
like image 123
Matt Ball Avatar answered Sep 23 '22 11:09

Matt Ball