Java Custom Annotations – Runtime and Compile / build time processing

Looking for a date or love? Click here to find one for free!!

Find Singapore Apartment  and Room Rentals here

India Stock Market blog

I am writing this as I learn about writing custom java annotations. I find that information about custom annotations and their processing is scattered and lengthy so I am summarizing the steps that is required to write a custom annotation and the ways to process it in a single place. I am also attaching the links to the tutorials and documents that I am referring to while I learn.

I hope this will help to get a high-level overview and also to refer back when in need. Use the given links for a detailed description of all the steps listed in this post

Steps to write a custom java annotation and process it either at run-time or compile time:

1. Declare the Annotation Type

- use @interface keyword to declare the Annotation
- add a method declaration for every element in the Annotation
- name the method as ‘value’ if the annotation has only one element
- add no declarations if is to act as a marker Annotation
- restrict return types to primitives, String, Class, enums, annotations, and arrays of the preceding types
- add no parameters and no throws clause
- specify any default values using ‘default’ keyword
- annotate this new type with meta-annotations like @Retention and @Target

2. Decorate the target classes and methods with the custom annotation

- use @NewAnnotationType( element key-value pairs separated by commas ) e.g @TryMe (name=”RK’, age=”24″, sex=”female”)
- if its a marker annotation then there is no need for the paranthesis
- if its an annotation with a single element then no need to use ‘key=value’ syntax e.g @TryMe(“Waiting for you!!”)

3. Process the custom Annotation. Annotations can be read from source files, class files, or reflectively at run time so there are few options and subsequently decisions to be made when it comes to the best way to process them for your application

Run Time:

- Use the new AnnotatedElement and Annotation interfaces added to the java reflection API to detect the presence of your annotation at run-time
- AnnotatedElement interface is in the java.lang.reflect package and implemented by the classes Class, Constructor, Field, Method, and Package
- AnnotatedElement interface has the following methods – getAnnotations(),getDeclaredAnnotations(),getAnnotation(Class<T>),isAnnotationPresent(Class<? extends Annotation>)
- Every annotation type automatically implements the java.lang.annotation.Annotation interface which happens in the background when the @interface keyword is used to declare a new annotation type

Compile Time with APT:

- Use APT (Annotation Processing Tool) command line utility that comes with Java 5. In Java 6 this is included as part of the compiler itself so there will be no need to use a tool explicitly. Overview in the sun’s document make it sound simple but implementing could be a little more complex than that. Here are the steps

1. Write a Processor that implements the com.sun.mirror.apt.AnnotationProcessor interface
2. Write a processor factory class that implements AnnotationProcessorFactory interface. This factory should use the AnnotationProcessorEnvironment object passed to it to return the AnnotationProcessor that can process the annotations present in the source file
3. Compile the processors and factories using javac with tools.jar on the classpath
4. Make the factory available to the apt tool either using the ‘-factory’ command line option or by using the ‘apt discovery’ procedure

Compile Time with javax.annotation.processing package:

- Use a custom annotation processor based on javax.annotation.processing package

1. Write a processor class that extends javax.annotation.processing.AbstractProcessor class
2. Specify the annotation that this custom processor is interested in. Can be done by either overriding the getSupportedAnnotationTypes() method of AbstractProcessor class or by annotating the custom class with @SupportedAnnotationTypes annotation.
3. Override the process() method
http://www.zdnetasia.com/techguide/java/0,39044898,39362483,00.htm is an excellent article you can refer to for more information on this

References and Sources :

Very good document about processing the Annotations – http://www.zdnetasia.com/techguide/java/0,39044898,39362483,00.htm
Another nice document – http://www.oracle.com/technology/pub/articles/hunter_meta_2.html &
http://www.oracle.com/technology/pub/articles/hunter_meta_3.html
SR 175: A Metadata Facility for the JavaTM Programming Language -  http://www.jcp.org/en/jsr/detail?id=175
Very Basic tutorial – http://java.sun.com/j2se/1.5.0/docs/guide/language/annotations.html
Document about the Annotation Processing Tool – http://java.sun.com/j2se/1.5.0/docs/guide/apt/index.html
Mirror API Specification – http://java.sun.com/j2se/1.5.0/docs/guide/apt/mirror/overview-summary.html
Good tutorial for Custom Annotations – http://www.ibm.com/developerworks/library/j-annotate2.html

RK

Find Singapore Apartment  and Room Rentals here

Looking for a date or love? Click here to find one for free!!

Stock Market Views, Experiences on http://theindiastockmarket.blogspot.com/

About yourmitra

I have started yourmitra on June 23rd 2007. This blog was started with the purpose to record the journey of my first web start-up yourmitra.com which has since then transformed into http://www.rentalandrealestate.com Now I write about anything under the sun in addition to sharing some information about my website.
This entry was posted in Technology and tagged , , , , , , , . Bookmark the permalink.

8 Responses to Java Custom Annotations – Runtime and Compile / build time processing

  1. rick says:

    useful…

  2. Tine says:

    Hi.
    I’m trying to learn annotations myself, and Iøm sorry, but your guide didn’t help at all. I need some examples!!

  3. Paul says:

    Is there a way to modify the annotation’s value at runtime?

    Thanks.

  4. Gangster30 says:

    James Midgley, editor of Mimesis. ,

  5. Pingback: Custom annotation « Nirvikalpa

  6. Tom says:

    Short, sweet and to the point.

    Helpful.

    Thanks.

  7. rashmi says:

    Hi, the description or summery provided is good. Can you please provide me examples of processors for more detailed learning.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s