2008 East
DIAMOND SPONSOR:
Data Direct
Frontiers in Data Access: The Coming Wave in Data Services
PLATINUM SPONSORS:
Red Hat
The Opening of Virtualization
Intel
Virtualization – Path to Predictive Enterprise
Green Hills
IT Security in a Hostile World
JBoss / freedom oss
Practical SOA Approach
GOLD SPONSORS:
Software AG
The Art & Science of SOA: How Governance Enables Adoption
PlateSpin
Effective Planning for Virtual Infrastructure Growth
Fujitsu
Automated Business Process Discovery & Virtualization Service
Ceedo
Workspace Virtualization
Click For 2007 West
Event Webcasts

2008 East
PLATINUM SPONSORS:
Appcelerator
Think Fast: Accelerate AJAX Development with Appcelerator
GOLD SPONSORS:
DreamFace Interactive
The Ultimate Framework for Creating Personalized Web 2.0 Mashups
ICEsoft
AJAX and Social Computing for the Enterprise
Kaazing
Enterprise Comet: Real–Time, Real–Time, or Real–Time Web 2.0?
Nexaweb
Now Playing: Desktop Apps in the Browser!
Sun
jMaki as an AJAX Mashup Framework
POWER PANELS:
The Business Value
of RIAs
What Lies Beyond AJAX?
KEYNOTES:
Douglas Crockford
Can We Fix the Web?
Anthony Franco
2008: The Year of the RIA
Click For 2007 Event Webcasts
SYS-CON.TV
TOP THREE LINKS YOU MUST CLICK ON


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

The 5.0 release of JDK introduced a slew of new features. A powerful technique that resulted from the JSR-175 recommendation is the Program Annotation Facility. It can annotate code in a standard way and automate the generation of source code or configuration files, helping cut down on boilerplate code.

At the moment, the closest thing to annotating source and generating support file/code is through java doc tags. The popular ones are @deprecated, @author, @param etc. However, these tags are pretty static by nature and the information they define isn't encoded in the class file by the compiler so it's not available at runtime. A popular implementation of this concept is XDoclet. This is an Open Source utility that lets a developer add metadata or attributes to source as java doc tags. Appropriate source files or configurations, such as deployment descriptors, are generated later using the ANT task provided by XDoclet. (The source code can be downloaded from www.sys-con.com/java/sourcec.cfm.)

The core Java language has always had some form of ad hoc annotation scheme. Java doc tags are an example. Another example is the keyword transient, which is used to mark a member variable so it can be ignored by the serialization subsystem.

All this changed with the introduction of JDK 5.0, which adds a general-purpose customizable annotation mechanism. This facility consists of syntax for declaring annotation types, syntax for annotating declarations, APIs for reading annotations, a class file representation for annotations and an annotation-processing tool.

Annotation and Annotation Types
The first step in the process is defining an annotation type. This is pretty simple to do and looks familiar as well. An annotation-type declaration looks like an interface declaration except an "@" symbol precedes the interface keyword. The method declaration that goes between the braces of this declaration defines the elements of the annotation type. Of course, since we are annotating the code and not defining behavior, logically speaking, these methods shouldn't throw any exception. That means no throws clause. Another restriction is that the return type for these methods is restricted to primitives: String, Class, enums, annotations and arrays of the preceding types. The complete lists of restrictions are as follows:

  • No extends clause is permitted.Annotation types automatically extend a marker interface, java.lang.annotation.Annotation.
  • Methods must not have any parameters.
  • Methods must not have any type parameters (in other words, generic methods are prohibited).
  • Method return types are restricted to primitive types: String, Class, enum types, annotation types and arrays of the preceding types.
  • No throws clause is permitted.
  • Annotation types must not be parameterized.
The following code snippet defines an annotation type for a servlet. Presumably, we could use this definition to annotate a servlet and then have an annotation tool generate web.xml. Here we define no args methods that define the various XML attributes/elements found in web.xml. For conciseness we have left out elements like init, load on startup, icon etc.


public @interface Servlet {
String servletName();
String servletClass();
String displayName();
String description();
}

Declaring Annotation
Now that we have the annotation-type defined we can annotate our servlet using the defined annotation type. Annotation is a new kind of modifier that contains an annotation type with zero or more member-value pairs. If a member has a default value defined in the annotation-type member declaration then the value can be omitted, otherwise, annotation must provide a member-value pair for all members defined in the annotation type. Annotation can be used for modifiers in any declaration - class, interface, constructor, method, field, enum, even local variable. It can also be used on a package declaration provided only one annotation is permitted for a given package. In our case we are annotating at the class level and the annotation precedes the access modifier public.


@Servlet(
servletName="AnnotatedServet",
servletClass="com.jdj.article.servlet.AnnotatedServet",
displayName="AnnotatedServet",
description="This is an example Annotated Servlet"
)
public class AnnotatedServet extends HttpServlet{...}

Now, to tie all these together we will look at how to build a simple annotation-driven framework. However, before we start looking at concrete code samples, we will go over a bit more of the theory behind this important addition to the core language API.

Meta Annotation Types
The API provides some annotation types out-of-the-box that can be used to annotate the annotation types. These standard annotation types are also known as meta-annotation types. The details are provided in Table 1.

Standard Annotation
The Tiger release of the JDK also bundles a set of standard annotation types. Table 2 defines the annotation tags and their purpose.

Annotation Retention
The consumers of annotation fall into three categories.

  • Introspectors: Programs that query runtime-visible annotations of their own program elements. These programs will load both annotated classes and annotation interfaces into the virtual machine.
  • Specific Tools: Programs that query known annotation types of arbitrary external programs. Stub generators, for example, fall into this category. These programs will read annotated classes without loading them into the virtual machine, but will load annotation interfaces.
  • General Tools: Programs that query arbitrary annotations of arbitrary external programs (such as compilers, documentation generators and class browsers). These programs will load neither annotated classes nor annotation interfaces into the virtual machine.
The grouping of annotation consu-mers mentioned above is determined by the retention policy that is specified by the RetentionPolicy enum present in the java.lang.annotation package. If the retention policy is 'CLASS' then the annota-tions are recorded in the class files but are not retained by the virtual machine. If the retention policy is 'RUNTIME' then the annotations are recorded in the class file and are retained by the VM at runtime. The value 'SOURCE' causes the compiler and VM to discard the annotation.
YOUR FEEDBACK
udaykiran wrote: 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 me.my id is udaykiranmca@gmail.com Thanks, udaykiranmca@gmail.com please send to this mail id .
Terry Corbet wrote: 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 tho...
Vish wrote: Bob, Sorry about that. Can you send me an email at unicode@yahoo.com, and I will send you the src Thanks,
Bob Shewan wrote: As Neil noted there isn't any source code in the zip file. Would you be kind enough to send what you have. Thanks Bob Shewan
vish krishnan wrote: 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 thanks
Neil Hornbeck wrote: The source zip file Viswanth1003.zip only contains compiled code.
LATEST JAVA STORIES & POSTS
Continuent has announced support and enhancements to MySQL Server 5.1.30 GA release, the 5.1 production version of the open source database. MySQL 5.1.30 is recommended for use on production systems by the MySQL build team at Sun Microsystems. Continuent Tungsten provides advance...
As a software journalist, there are times when certain vendors will shut the door on reporting opportunities that might represent too much of an "inside view" of their technology or their organization. I've been to more developer events than I can remember where I've been handed ...
Active Endpoints has announced the general availability of ActiveVOS 6.0.2, in response to ever increasing demands for improved process performance and efficiencies. ActiveVOS is an all-in-one, 100% standards-based orchestration and business process management system (BPM) that p...
Just because the web has been open so far doesn't mean that it will stay that way. Flash and Silverlight, arguably the two market-leading technology toolkits for rich media applications are not open. Make no mistake - Microsoft and Adobe aim to have their proprietary plug-ins, ak...
Doing network I/O on the user interface (UI) thread is bad. Most developers know that and can tell you why; unfortunately, it’s still done. At this year's JavaOne, one of the keynote JavaFX demos bombed because the network was slow, something that would be forgivable had the en...
Over the course of the past few decades, the consumer media industry has evolved from a slow-moving oligopoly dominated by a handful of vertically integrated networks to a highly fragmented and competitive marketplace of content creation, publication, and distribution players. Th...
SUBSCRIBE TO THE WORLD'S MOST POWERFUL NEWSLETTERS
SUBSCRIBE TO OUR RSS FEEDS & GET YOUR SYS-CON NEWS LIVE!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021


SYS-CON FEATURED WHITEPAPERS

SPONSORED BY INFRAGISTICS
In every field of design one of the first things students do is learn from the work of others. They ...
There are many forces that influence technological evolution. After a decade of building enterprise ...
2008 is going to be an important year for Rich Internet Applications. Most organizations are deliver...
The OpenAjax Alliance is developing an Ajax industry wishlist for future browsers, using a dedicated...
Infragistics announced the availability of two Community Technology Preview (CTP) User Interface (UI...
The YUI development team has released version 2.5.2; you can download the new release from SourceFor...
ADS BY GOOGLE