Java Reference
In-Depth Information
Listing 1-19 shows the code that you need to save in a package-info.java file and compile it along with other
programs. It annotates the com.jdojo.annotation package. Listing 1-20 has the code for a class for demonstration
purpose that has some annotations. Listing 1-21 is the program that demonstrates how to access annotations at
runtime. Its output shows that you are able to read all annotations used in the AccessAnnotation class successfully.
The printAnnotations() method accesses the annotations. It accepts a parameter of the AnnotatedElement type and
prints all annotations of its parameter. If the annotation is of the Version annotation type, it prints the values for its
major and minor versions.
Listing 1-19. Contents of package-info.java File
// package-info.java
@Version(major=1, minor=0)
package com.jdojo.annotation;
Listing 1-20. AccessAnnotation Class Has Some Annotations, Which Will Be Accessed at Runtime
// AccessAnnotation.java
package com.jdojo.annotation;
@Version(major=1, minor=0)
public class AccessAnnotation {
@Version(major=1, minor=1)
public void testMethod1() {
// Code goes here
}
@Version(major=1, minor=2)
@Deprecated
public void testMethod2() {
// Code goes here
}
}
Listing 1-21. Using the AccessAnnotationTest Class to Access Annotations
// AccessAnnotationTest.java
package com.jdojo.annotation;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
public class AccessAnnotationTest {
public static void main(String[] args) {
// Read annotation of class declaration
Class<AccessAnnotation> c = AccessAnnotation.class;
System.out.println("Annotations for class:" + c.getName());
printAnnotations(c);
// Read annotation of package declaration
Package p = c.getPackage();
System.out.println("Annotations for package:" + p.getName());
printAnnotations(p);
 
Search WWH ::




Custom Search