Java Reference
In-Depth Information
// Get all annotations on the class declaration
Annotation[] allAnns = c.getAnnotations();
System.out.println("Annotation count: " + allAnns.length);
// Print all annotations
for (Annotation ann : allAnns) {
System.out.println(ann);
}
The
toString()
method of the
Annotation
interface returns the string representation of an annotation. Suppose
you want to print the
Version
annotation on the
Test
class. You can do so as follows. The following code shows that
you can use the
major()
and
minor()
methods. It also shows that you can declare a variable of an annotation type
(e.g.
Version v
), which can refer to an instance of that annotation type. The instances of an annotation type are
created by the Java runtime. You never create an instance of an annotation type using the
new
operator.
Class<Test> c = Test.class;
// Get the instance of the Version annotation of Test class
Version v = c.getAnnotation(Version.class);
if (v == null) {
System.out.println("Version annotation is not present.");
}
else {
int major = v.major();
int minor = v.minor();
System.out.println("Version: major=" + major + ", minor=" + minor);
}
You will use the
Version
and
Deprecated
annotation types to annotate your program elements, and access those
annotations at runtime. You will also annotate a package declaration and a method declaration. You will use the code
for the
Version
annotation type as listed in Listing 1-18. Note that it uses the
@Retention(RetentionPolicy.RUNTIME)
annotation, which is needed to read its instances at runtime.
Listing 1-18.
A Version Annotation Type
// Version.java
package com.jdojo.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Target({ElementType.TYPE, ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PACKAGE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Version {
int major();
int minor();
}