Datasheet

process(cls.annotations());
System.out.println();
for(MethodDoc m : cls.methods()) {
System.out.println(“Annotations for method [“ + m + “]”);
process(m.annotations());
System.out.println();
}
}
static void process(AnnotationDesc[] anns)
{
for (AnnotationDesc ad : anns) {
AnnotationDesc.ElementValuePair evp[] = ad.elementValues();
for(AnnotationDesc.ElementValuePair e : evp) {
System.out.println(“ NAME: “ + e.element() +
“, VALUE=” + e.value());
}
}
}
}
The start method iterates across all classes (and interfaces) found in the source file. Because all annota-
tions on source code elements are associated with the
AnnotationDesc interface, a single method can
be written to process annotations regardless of with which source code element the annotation is associ-
ated. The
showAnnotations method prints out annotations associated with the current class and then
processes all methods inside that class. The doclet API makes processing these source code elements
easy. To execute the doclet, pass the name of the doclet and name of the class to process on the command
line as follows:
javadoc -doclet AnnotationViewer ServerCommandProcessor.java
The doclet echoes the following to the screen:
Loading source file ServerCommandProcessor.java...
Constructing Javadoc information...
Annotations for class [ServerCommandProcessor]
NAME: CodeTag.authorName(), VALUE=”Dilbert”
NAME: CodeTag.lastModificationDate(), VALUE=”May 7, 2006”
Annotations for method [ServerCommandProcessor.setParams(java.lang.String)]
NAME: CodeTag.authorName(), VALUE=”Dilbert”
NAME: CodeTag.lastModificationDate(), VALUE=”May 10, 2006”
NAME: CodeTag.bugFixes(), VALUE=”BUG0170”
Annotations for method [ServerCommandProcessor.executeCommand(java.lang.String,
java.lang.Object[])]
To access annotations at runtime, the reflection API must be used. This support is built in through the
interface
AnnotatedElement, which is implemented by the reflection classes AccessibleObject,
Class, Constructor, Field, Method, and Package. All these elements may have annotations. The
AnnotatedElement interface defines the following methods.
31
Chapter 1: Key Java Language Features and Libraries
05_777106 ch01.qxp 11/28/06 10:43 PM Page 31