Friday October 21, 2005
Joseph D. Darcy's Sun WeblogJoseph D. Darcy's Sun Weblog JSR 269 in Mustang Build 57 The initial reference implementation of JSR 269 shipped as part of Mustang build 57! JSR 269 has two basic pieces, an API that models the Java programming language and an API for writing annotation processors. Those pieces are in the new packages javax.lang.model.* and javax.annotation.processing, respectively. The JSR 269 functionality is accessed by using new options to the javac command. By including JSR 269 support, the javac command now acts analogously to the apt command in Sun's JDK 5. To get an overview of annotation processing, see our 2005 JavaOne session on that topic. Annotation processing is now enabled by default in javac; we designed our implementation of JSR 269 so that there should only be negligible speed impact on javac when no annotation processors are run. To just run annotation processing without compiling source code to class files, use the -proc:only option. Writing your first annotation processorAnnotation processing is a form of meta-programming, that is, programming based on the structure of a program. However, for starters, let's consider a "Hello World" annotation processor:
import javax.annotation.processing.*;
import static javax.lang.model.SourceVersion.*;
import javax.lang.model.element.*;
import javax.lang.model.type.*;
import javax.lang.model.util.*;
import java.util.Set;
@SupportedAnnotationTypes("*") // Process all annotations
@SupportedSourceVersion(RELEASE_6)
public class HelloWorldProcessor extends AbstractProcessor {
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
if (!roundEnv.processingOver())
processingEnv.getMessager().printNotice("Hello World");
return false; // Don't claim any annotations
}
}
To compile this program, add tools.jar to the classpath of javac:javac -cp Path-to-tools.jar HelloWorldProcessor.java (We plan to make adding tools.jar to the classpath more
convenient in the future.) To run the annotation processor, use
the new -processor option to javac: The output should include: Note: Hello World(HelloWorldProcessor can be run against HelloWorldProcessor.java; to do so, both tools.jar and the class files for HelloWorldProcessor need to be on the classpath.) This simple annotation processor doesn't actually examine the structure of a program, but it illustrates a few points about how to write and run annotation processors:
Future Topics"Hello World" just scratches the surface of what annotation processors can do! For example, annotation processors can
|
Calendar
RSS Feeds
All /Annotation Processing /General /Java /JavaOne /Numerics /OpenJDK SearchLinks
NavigationReferersToday's Page Hits: 218 |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||