- 10.1. Scripting for the Java Platform
- 10.2. The Compiler API
- 10.3. Using Annotations
- 10.4. Annotation Syntax
- 10.5. Standard Annotations
- 10.6. Source-Level Annotation Processing
- 10.7. Bytecode Engineering
10.6. Source-Level Annotation Processing
One use for annotation is the automatic generation of “side files” that contain additional information about programs. In the past, the Enterprise Edition of Java was notorious for making programmers fuss with lots of boilerplate code. Modern versions of Java EE use annotations to greatly simplify the programming model.
In this section, we demonstrate this technique with a simpler example. We write a program that automatically produces bean info classes. You tag bean properties with an annotation and then run a tool that parses the source file, analyzes the annotations, and writes out the source file of the bean info class.
Recall from Chapter 8 that a bean info class describes a bean more precisely than the automatic introspection process can. The bean info class lists all of the properties of the bean. Properties can have optional property editors. The ChartBeanBeanInfo class in Chapter 8 is a typical example.
To eliminate the drudgery of writing bean info classes, we supply an @Property annotation. You can tag either the property getter or setter, like this:
@Property String getTitle() { return title; }
or
@Property(editor="TitlePositionEditor") public void setTitlePosition(int p) { titlePosition = p; }
Listing 10.12 contains the definition of the @Property annotation. Note that the annotation has a retention policy of SOURCE. We analyze the annotation at the source level only. It is not included in class files and not available during reflection.
Listing 10.12. sourceAnnotations/Property.java
1 package sourceAnnotations; 2 import java.lang.annotation.*; 3 4 @Documented 5 @Target(ElementType.METHOD) 6 @Retention(RetentionPolicy.SOURCE) 7 public @interface Property 8 { 9 String editor() default ""; 10 }
To automatically generate the bean info class of a class with name BeanClass, we carry out the following tasks:
- Write a source file BeanClassBeanInfo.java. Declare the BeanClassBeanInfo class to extend SimpleBeanInfo, and override the getPropertyDescriptors method.
- For each annotated method, recover the property name by stripping off the get or set prefix and “decapitalizing” the remainder.
- For each property, write a statement for constructing a PropertyDescriptor.
- If the property has an editor, write a method call to setPropertyEditorClass.
- Write the code for returning an array of all property descriptors.
For example, the annotation
@Property(editor="TitlePositionEditor") public void setTitlePosition(int p) { titlePosition = p; }
in the ChartBean class is translated into
public class ChartBeanBeanInfo extends java.beans.SimpleBeanInfo { public java.beans.PropertyDescriptor[] getProperties() { java.beans.PropertyDescriptor titlePositionDescriptor = new java.beans.PropertyDescriptor("titlePosition", ChartBean.class); titlePositionDescriptor.setPropertyEditorClass(TitlePositionEditor.class) . . . return new java.beans.PropertyDescriptor[] { titlePositionDescriptor, . . . } } }
(The boilerplate code is printed in the lighter gray.)
All this is easy enough to do, provided we can locate all methods that have been tagged with the @Property annotation.
As of Java SE 6, you can add annotation processors to the Java compiler. (In Java SE 5, a stand-alone tool, called apt, was used for the same purpose.) To invoke annotation processing, run
javac -processor ProcessorClassName1,ProcessorClassName2,. . . sourceFiles
The compiler locates the annotations of the source files. It then selects the annotation processors that should be applied. Each annotation processor is executed in turn. If an annotation processor creates a new source file, then the process is repeated. Once a processing round yields no further source files, all source files are compiled. Figure 10.3 shows how the @Property annotations are processed.
Figure 10.3. Processing source-level annotations
We do not discuss the annotation processing API in detail, but the program in Listing 10.13 will give you a flavor of its capabilities.
An annotation processor implements the Processor interface, generally by extending the AbstractProcessor class. You need to specify which annotations your processor supports. The designers of the API themselves love annotations, so they use an annotation for this purpose:
@SupportedAnnotationTypes("com.horstmann.annotations.Property") public class BeanInfoAnnotationProcessor extends AbstractProcessor
A processor can claim specific annotation types, wildcards such as "com.horstmann.* “(all annotations in the com.horstmann package or any subpackage), or even "*" (all annotations).
The BeanInfoAnnotationProcessor has a single public method, process, that is called for each file. The process method has two parameters: the set of annotations that is being processed in this round, and a RoundEnv reference that contains information about the current processing round.
In the process method, we iterate through all annotated methods. For each method, we get the property name by stripping off the get, set, or is prefix and changing the next letter to lower case. Here is the outline of the code:
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { for (TypeElement t : annotations) { Map<String, Property> props = new LinkedHashMap<String, Property>(); for (Element e : roundEnv.getElementsAnnotatedWith(t)) { props.put(property name, e.getAnnotation(Property.class)); } } write bean info source file return true; }
The process method should return true if it claims all the annotations presented to it; that is, if those annotations should not be passed on to other processors.
The code for writing the source file is straightforward—just a sequence of out.print statements. Note that we create the output writer as follows:
JavaFileObject sourceFile = processingEnv.getFiler().createSourceFile(beanClassName + "BeanInfo"); PrintWriter out = new PrintWriter(sourceFile.openWriter());
The AbstractProcessor class has a protected field processingEnv for accessing various processing services. The Filer interface is responsible for creating new files and tracking them so that they can be processed in subsequent processing rounds.
When an annotation processor detects an error, it uses the Messager to communicate with the user. For example, we issue an error message if a method has been annotated with @Property but its name doesn’t start with get, set, or is:
if (!found) processingEnv.getMessager().printMessage(Kind.ERROR, "@Property must be applied to getXxx, setXxx, or isXxx method", e);
In the companion code for this book, we supply an annotated file, ChartBean.java. Compile the annotation processor:
javac sourceAnnotations/BeanInfoAnnotationProcessor.java
Then run
javac -processor sourceAnnotations.BeanInfoAnnotationProcessor chart/ChartBean.java
and have a look at the automatically generated file ChartBeanBeanInfo.java.
To see the annotation processing in action, add the command-line option XprintRounds to the javac command. You will get this output:
Round 1: input files: {com.horstmann.corejava.ChartBean} annotations: [com.horstmann.annotations.Property] last round: false Round 2: input files: {com.horstmann.corejava.ChartBeanBeanInfo} annotations: [] last round: false Round 3: input files: {} annotations: [] last round: true
This example demonstrates how tools can harvest source file annotations to produce other files. The generated files don’t have to be source files. Annotation processors may choose to generate XML descriptors, property files, shell scripts, HTML documentation, and so on.
Listing 10.13. sourceAnnotations/BeanInfoAnnotationProcessor.java
1 package sourceAnnotations; 2 3 import java.beans.*; 4 import java.io.*; 5 import java.util.*; 6 import javax.annotation.processing.*; 7 import javax.lang.model.*; 8 import javax.lang.model.element.*; 9 import javax.tools.*; 10 import javax.tools.Diagnostic.*; 11 12 /** 13 * This class is the processor that analyzes Property annotations. 14 * @version 1.11 2012-01-26 15 * @author Cay Horstmann 16 */ 17 @SupportedAnnotationTypes("sourceAnnotations.Property") 18 @SupportedSourceVersion(SourceVersion.RELEASE_7) 19 public class BeanInfoAnnotationProcessor extends AbstractProcessor 20 { 21 @Override 22 public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) 23 { 24 for (TypeElement t : annotations) 25 { 26 Map<String, Property> props = new LinkedHashMap<>(); 27 String beanClassName = null; 28 for (Element e : roundEnv.getElementsAnnotatedWith(t)) 29 { 30 String mname = e.getSimpleName().toString(); 31 String[] prefixes = { "get", "set", "is" }; 32 boolean found = false; 33 for (int i = 0; !found && i < prefixes.length; i++) 34 if (mname.startsWith(prefixes[i])) 35 { 36 found = true; 37 int start = prefixes[i].length(); 38 String name = Introspector.decapitalize(mname.substring(start)); 39 props.put(name, e.getAnnotation(Property.class)); 40 } 41 42 if (!found) processingEnv.getMessager().printMessage(Kind.ERROR, 43 "@Property must be applied to getXxx, setXxx, or isXxx method", e); 44 else if (beanClassName == null) 45 beanClassName = ((TypeElement) e.getEnclosingElement()).getQualifiedName() 46 .toString(); 47 } 48 try 49 { 50 if (beanClassName != null) writeBeanInfoFile(beanClassName, props); 51 } 52 catch (IOException e) 53 { 54 e.printStackTrace(); 55 } 56 } 57 return true; 58 } 59 60 /** 61 * Writes the source file for the BeanInfo class. 62 * @param beanClassName the name of the bean class 63 * @param props a map of property names and their annotations 64 */ 65 private void writeBeanInfoFile(String beanClassName, Map<String, Property> props) 66 throws IOException 67 { 68 JavaFileObject sourceFile = processingEnv.getFiler().createSourceFile( 69 beanClassName + "BeanInfo"); 70 PrintWriter out = new PrintWriter(sourceFile.openWriter()); 71 int i = beanClassName.lastIndexOf("."); 72 if (i > 0) 73 { 74 out.print("package "); 75 out.print(beanClassName.substring(0, i)); 76 out.println(";"); 77 } 78 out.print("public class "); 79 out.print(beanClassName.substring(i + 1)); 80 out.println("BeanInfo extends java.beans.SimpleBeanInfo"); 81 out.println("{"); 82 out.println(" public java.beans.PropertyDescriptor[] getPropertyDescriptors()"); 83 out.println(" {"); 84 out.println(" try"); 85 out.println(" {"); 86 for (Map.Entry<String, Property> e : props.entrySet()) 87 { 88 out.print(" java.beans.PropertyDescriptor "); 89 out.print(e.getKey()); 90 out.println("Descriptor"); 91 out.print(" = new java.beans.PropertyDescriptor(\""); 92 out.print(e.getKey()); 93 out.print("\", "); 94 out.print(beanClassName); 95 out.println(".class);"); 96 String ed = e.getValue().editor().toString(); 97 if (!ed.equals("")) 98 { 99 out.print(" "); 100 out.print(e.getKey()); 101 out.print("Descriptor.setPropertyEditorClass("); 102 out.print(ed); 103 out.println(".class);"); 104 } 105 } 106 out.println(" return new java.beans.PropertyDescriptor[]"); 107 out.print(" {"); 108 boolean first = true; 109 for (String p : props.keySet()) 110 { 111 if (first) first = false; 112 else out.print(","); 113 out.println(); 114 out.print(" "); 115 out.print(p); 116 out.print("Descriptor"); 117 } 118 out.println(); 119 out.println(" };"); 120 out.println(" }"); 121 out.println(" catch (java.beans.IntrospectionException e)"); 122 out.println(" {"); 123 out.println(" e.printStackTrace();"); 124 out.println(" return null;"); 125 out.println(" }"); 126 out.println(" }"); 127 out.println("}"); 128 out.close(); 129 } 130 }