Digital Edition

Java Annotation Facility - A Primer
JDK 5 Has Changed Source Code Generation in a Seminal Way

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.

Using Annotation for Generating Struts-config.xml
For a concrete understanding of the technology it's imperative that we dive into writing code and see for ourselves how it works. We will look at how to go about generating struts-config.xml by annotating code and using the apt tool. This article assumes that the reader is familiar with the Open Source MVC framework struts. We will look at how to generate the configuration details and the declarative programming semantics provided in the struts-config.xml by annotating the source code.

Before we get to the nitty-gritty of annotating and generating configuration files, we need to understand why this needs to be done.

We need to do this because a developer who has to write code using the struts framework finds himself copying and pasting information from the source code to the deployment descriptor and vice versa. For instance, if we change the name of the Action class and don't change the XML file, the application doesn't work correctly. The way to sidestep this issue is to isolate the changes to one location and let the utility tool generate the deployment descriptor. We will cover how to use the metadata facility to achieve this automatic configuration file generation.

Before we start we have to make sure that we have the right development tools to do what we're trying to do. Currently very few IDEs support Java 5. Among Open Source IDEs, NetBeans 4.0 beta 2 looks promising (in spite of a few runtime exceptions) so most of the code in this article was written and tested with it. The first step in the process is defining the annotation types for the various elements that make up the struts framework. The component parts of the framework are: Action, Form bean (also known as Action Forms), Exceptions, Validator, Plug-ins etc.

The annotation type for Struts Action is as follows:

package com.jdj.article.atypes;
import java.lang.annotation.*;

public @interface StrutsAction {
String name();
String path();
String scope() default "session";
String input() default "";
String roles() default "";
String validate() default "";
String parameter() default "";
StrutsActionForward[] forward();
StrutsActionException strutsAction

As you can see, I have the annotation types as return types. This is necessary because we could have forward and exception elements defined by the action element. The XML snippet from that struts-config.xml that we're trying to generate will clarify the need for embedding other annotation types in the action annotation-type declaration.

<action path="/SubmitLogon"
<forward name="failure" path="/"/>
<forward name="success" path="/
<exception key="expired.password"

The next step is to annotate the code with the annotation type. In our case we will annotate a struts action class. This is done as follows:

package ....
import ....
name=" example.LogonAction",
forward = {@StrutsActionForward(
name = "failure",
path = "/" )},
strutsActionException =
key = "expired.password",
type = "example.ExpiredPassword
path = "/"
public class ExampleAction extends Action {

/** Creates a new instance of ExampleAction */
public ExampleAction() {

public ActionForward execute(ActionMapping
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
return null;

In order to post a comment you need to be registered and logged in.

Register | Sign-in

Reader Feedback: Page 1 of 1

Really Excellent Information. But i have some doubts. initially i have some aversion towards annotations but after reading this article i develop some interest on it. later my R & D i want to create an annotation which is like @Singleton when ever i applied this annotation for a class then i want to make a class as singleton class. could you please help me out from this scenario.

in the same way @ThrowException(exceptionType="ArithmeticException.class")

many more ideas but i couldn't able to move in forward direction because there is no much information about annotations in Google also.
even no where i found the source code of this article. if you have any please send me complete source code with compilation and execution instructions. please please its really great help for id is

please send to this mail id .

This is a critique for the editor, not the author.

A primer that uses for an example something that requires experience with Struts is not what you should have provided. Ok, so the guy you got to do all the hard work happened to be interested in solving a Struts problem, but your job, as editor, should have been to carefully think through the issues of documenting this new Java facility and providing examples with as little dependence upon some specific toolkit-framework-environment as possible. With Mustang about to add to the value of annotation, I am sure there is much need for carefully-thought-out articles demonstrating valuable, incremental information. When K&R contrived 'Hello World', it was after thoughtful consideration about learning processes. Combined with the fact that the source code was not correctly provided, the overall impression is that you, as an editor, just thought you could get something for nothing and pass it along where enough Google hits would provide the mass of advertising that is blinking all around me as I enter this suggestion.


Sorry about that. Can you send me an email at, and I will send you the src


As Neil noted there isn't any source code in the zip file. Would you be kind enough to send what you have.


Bob Shewan

Neil, sorry about that. Send me an email and I will send you all the source that I have got. My email is unicode at yahoo dot com (OR) krviswanath at Deloitte dot com


The source zip file only contains compiled code.

Subscribe to the World's Most Powerful Newsletters


Modern software design has fundamentally changed how we manage applications, causing many to turn to...
In this presentation, you will learn first hand what works and what doesn't while architecting and d...
In an era of historic innovation fueled by unprecedented access to data and technology, the low cost...
In his session at 20th Cloud Expo, Mike Johnston, an infrastructure engineer at, discu...
Everyone wants the rainbow - reduced IT costs, scalability, continuity, flexibility, manageability, ...
DXWorldEXPO | CloudEXPO are the world's most influential, independent events where Cloud Computing w...
Founded in 2000, Chetu Inc. is a global provider of customized software development solutions and IT...
DevOpsSummit New York 2018, colocated with CloudEXPO | DXWorldEXPO New York 2018 will be held Novemb...
Most DevOps journeys involve several phases of maturity. Research shows that the inflection point wh...
SYS-CON Events announced today that DatacenterDynamics has been named “Media Sponsor” of SYS-CON's 1...
CloudEXPO New York 2018, colocated with DXWorldEXPO New York 2018 will be held November 11-13, 2018,...
Dynatrace is an application performance management software company with products for the informatio...
DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, ...
@DevOpsSummit at Cloud Expo, taking place November 12-13 in New York City, NY, is co-located with 22...
Today, we have more data to manage than ever. We also have better algorithms that help us access our...
Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: D...
A valuable conference experience generates new contacts, sales leads, potential strategic partners a...
DXWorldEXPO LLC announced today that ICOHOLDER named "Media Sponsor" of Miami Blockchain Event by Fi...
SYS-CON Events announced today that IoT Global Network has been named “Media Sponsor” of SYS-CON's @...
The best way to leverage your Cloud Expo presence as a sponsor and exhibitor is to plan your news an...