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?
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.
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.
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.
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 { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With