Java Reference
In-Depth Information
You may need some import statement to import annotation types or you can use the fully qualified names of the
annotation types in the package-info.java file. Even though the import statement appears after the package declaration,
it should be okay to use the imported types. You can have contents like the following in a package-info.java file:
// package-info.java
@com.jdojo.myannotations.Author("John Jacobs")
@Reviewer("Wally Inman")
package com.jdojo.annotation;
import com.jdojo.myannotations.Reviewer;
Accessing Annotations at Runtime
Accessing annotation on a program element is easy. Annotations on a program element are Java objects. All you need
to know is how to get the reference of objects of an annotation type at runtime. Program elements that let you access
their annotations implement the java.lang.reflect.AnnotatedElement interface. There are several methods in the
AnnotatedElement interface that let you access annotations of a program element. The methods in this interface let
you retrieve all annotations on a program element, all declared annotations on a program element, and annotations
on a program element of a specified type. I will show some examples of using those methods shortly. The following
classes implement the AnnotatedElement interface:
java.lang.Class
java.lang.reflect.Executable
java.lang.reflect.Constructor
java.lang.reflect.Field
java.lang.reflect.Method
java.lang.reflect.Parameter
java.lang.Package
java.lang.reflect.AccessibleObject
Methods of the AnnotatedElement interface are used to access annotation on the above-listed types of objects.
it is very important to note that an annotation type must be annotated with the Retention meta-annotation
with the retention policy of runtime to access it at runtime. if a program element has multiple annotations, you would be
able to access only annotations, which have runtime as their retention policy.
Caution
Suppose you have a Test class and you want to print all its annotations. The following snippet of code will print
all annotations on the class declaration of the Test class:
// Get the class object reference
Class<Test> c = Test.class;
 
 
Search WWH ::




Custom Search