Home > Articles > Programming > Java

This chapter is from the book

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:

  1. Write a source file BeanClassBeanInfo.java. Declare the BeanClassBeanInfo class to extend SimpleBeanInfo, and override the getPropertyDescriptors method.
  2. For each annotated method, recover the property name by stripping off the get or set prefix and “decapitalizing” the remainder.
  3. For each property, write a statement for constructing a PropertyDescriptor.
  4. If the property has an editor, write a method call to setPropertyEditorClass.
  5. 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

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 }

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020