Digital Edition

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

Before tackling how to generate code or other dependent files such as deployment descriptor, we should clarify a couple of aspects presented in the code snippet above. The StrutsAction annotation type defines many elements but only a few of them were actually declared in the real annotation. This is perfectly valid because the elements that don't have a value declared will take the default value defined in the annotation type. In this case most of the values defaulted to an empty string but the scope element has a default value of session. So if the developer doesn't explicitly specify the value, the default value will be used. In the StrutsAction annotation type, we also have the return type for the forward element as an array of StrutsActionForward elements. So annotation is done by separating the values by a comma wrapped in braces.

forward = {@StrutsActionForward( ... ),
@StrutsActionForward( ... ) },

In this code snippet two action forward element are specified and both of them are enclosed by a brace separated by a comma. Now that we've talked about annotation types and annotation, the core concepts of annotation have been pretty much covered.

Generating Code/Supporting Files
The final steps in the process are the procedures for generating code or support files like deployment descriptor. This could be the hardest part depending on the complexity of what we are trying to do. If we are generating source code based on annotation information then we need to have some kind of parser generator to generate the code. JavaCC hosted at is an excellent parser generator implementation. Since we are generating an XML file, we used JDOM API to generate the deployment descriptor for struts.

There are two ways to do the code generation. The first is to write a driver code that uses the reflection API and the annotation API to figure out what annotations are present and then operate on them appropriately. The other is to use the annotation processing tool bundled with the JDK to process the annotation.

In the section above we explained how the annotation processing tool works. The annotation processor that's returned by the factory does the actual work of generating code. In the core processing we loop through the annotation types and have a visitor based on the Gang of Four's visitor design pattern do the work. This visitor processes the annotation on the class declaration, method declaration, package declarations etc. and does the file generation.

The code snippet for the factory, annotation processor and a simple visitor is as follows:

public class StrutsConfigGenerator implements
private static final Collection<String>
= unmodifiableCollection(Arrays.asList("*"));
private static final Collection<String>
supportedOptions = emptySet();
public StrutsConfigGenerator() {}

public Collection<String> supported
AnnotationTypes() {
return supportedAnnotations;

public Collection<String> supported
Options() {
return supportedOptions;

public AnnotationProcessor get
Declaration> atds,
Environment env) {
return (AnnotationProcessor)new

private static class WebGeneratedAp
AnnotationProcessor {
private final AnnotationProcessor
Environment env;
Environment env) {}

public void process() {
for (TypeDeclaration typeDecl :
// GoF visitor Design Pattern
applied here!
new WebGeneratorClass
Visitor(), NO_OP));
private class WebGeneratorClassVisitor
SimpleDeclarationVisitor {
public WebGeneratorClassVisitor(){ }

public void visitClassDeclaration(
ClassDeclaration d)
/ /Do some meaningful work here!!!

// You could have more specific declarations here

An important thing that we need to take note of is the getProcessorFor method in the factory. This method returns the annotation processor and, in our case, is an instance of the WebGeneratedAp class. This class extends AnnotationProcessor and implements the no args process method. Here we loop through all the type declarations and then have the type declaration accept our visitor. Our visitor is WebGeneratorClassVisitor and has methods to handle the areas where annotations occur like class declaration, method declaration and package declaration. It's here that we read the annotation, find out what the value is and operate on it accordingly. The complete working copy of the source is provided along with this article.

The final step in the process is to invoke the Annotation Processing Tool. This is typically done through the command line as follows:

apt -cp [Classpath] -nocompile
-factory com.jdj.article.gen.StrutsConfigGenerator
generated\struts-config.xml <path>\

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


Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As au...
DXWorldEXPO LLC announced today that "Miami Blockchain Event by FinTechEXPO" has announced that its ...
DXWorldEXPO | CloudEXPO are the world's most influential, independent events where Cloud Computing w...
The best way to leverage your Cloud Expo presence as a sponsor and exhibitor is to plan your news an...
DevOpsSummit New York 2018, colocated with CloudEXPO | DXWorldEXPO New York 2018 will be held Novemb...
With 10 simultaneous tracks, keynotes, general sessions and targeted breakout classes, @CloudEXPO an...
Cloud Expo | DXWorld Expo have announced the conference tracks for Cloud Expo 2018. Cloud Expo will ...
DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, ...
@DevOpsSummit New York 2018, colocated with CloudEXPO | DXWorldEXPO New York 2018 will be held Novem...
The dynamic nature of the cloud means that change is a constant when it comes to modern cloud-based ...
"We started a Master of Science in business analytics - that's the hot topic. We serve the business ...
DXWorldEXPO LLC announced today that Dez Blanchfield joined the faculty of CloudEXPO's "10-Year Anni...
There is a huge demand for responsive, real-time mobile and web experiences, but current architectur...
The standardization of container runtimes and images has sparked the creation of an almost overwhelm...
We call it DevOps but much of the time there’s a lot more discussion about the needs and concerns of...
As DevOps methodologies expand their reach across the enterprise, organizations face the daunting ch...
"NetApp is known as a data management leader but we do a lot more than just data management on-prem ...
"Since we launched LinuxONE we learned a lot from our customers. More than anything what they respon...
Modern software design has fundamentally changed how we manage applications, causing many to turn to...
As you move to the cloud, your network should be efficient, secure, and easy to manage. An enterpris...