Use annotation in Java(二)

2014-11-24 11:24:52 · 作者: · 浏览: 12
ograms that query arbitrary annotations of arbitrary external programs (such as compilers, documentation generators and class browsers). These programs will load neither annotated classes nor annotation interfaces into the virtual machine.
The grouping of annotation consumers mentioned above is determined by the retention policy that is specified by the RetentionPolicy enum present in the java.lang.annotation package. If the retention policy is 'CLASS' then the annotations are recorded in the class files but are not retained by the virtual machine. If the retention policy is 'RUNTIME' then the annotations are recorded in the class file and are retained by the VM at run-time. The value 'SOURCE' causes the compiler and VM to discard the annotation.
Annotation Processing Tool
The annotation processing tool (apt) found in JAVA_HOME/bin directory is a command-line utility that ships with JDK 5.0. This tool looks for annotation processors based on the annotation in the set of specified source files being examined. Essentially the annotation processor uses a set of reflective APIs and supporting infrastructure to process the annotations.
When invoked, the apt goes through the following sequence of operations: First, it determines what annotations are present in the source code being operated on. Next, it looks for annotation processor factories. It then asks the factories what annotations they process and, if the factory processes an annotation present in source files being operated on, the apt asks the factory to provide an annotation processor. Next, the annotation processors are run. If the processors have generated new source files, the apt will repeat this process until no new source files are generated. This high-level sequence is indicated in Figure 1.
To write a factory class, a developer has to rely on packages that aren't part of the standard SDK. The packages used are:
com.sun.mirror.apt: interfaces to interact with the tool.
com.sun.mirror.declaration: interfaces to model the source code declarations of fields, methods, classes, etc.
com.sun.mirror.type: interfaces to model types found in the source code.
com.sun.mirror.util: various utilities for processing types and declarations, including visitors.
These packages are bundled in tools.jar, and so this jar file needs to be set in the classpath to write and compile the factory class. Assuming that the path and the classpath are set correctly, the annotation processing tool can be invoked from the command prompt by typing 'apt' followed by the tools command-line parameters.