Archive

Posts Tagged ‘annotatios’

How Java Annotations Works

April 20th, 2009

java_annotationsThis article explains what are Java Annotations, How to define and use Java Annotation and how Java Annotations works. Java annotations are meta data provides data about a program that is not part of the program itself. They have no direct impact on the operations of the code they annotate. An annotation indicates that the declared element( can be field, class, method, package etc..,) should be processed in some special way by a compiler, development tool, deployment tool, or during runtime. To develop APIs require a fair amount of coding. For example, in order to write a JAX-RPC web service, we must provide a paired interface and implementation. This code could be generated automatically by a tool if the program were “decorated” with annotations indicating which methods were remotely accessible.

We can make our APIs less error-prone using annotations. Many APIs require additional files to be maintained in parallel with programs. For example, “JavaBean” requires a “AdditionalInfo” class to be maintained in parallel with it and Enterprise Java Bean (EJB) requires deployment descriptor.

The Java platform has always had various ad hoc annotation mechanisms. For example, the @deprecated javadoc tag is an ad hoc annotation indicating that the method should no longer be used, and the transient modifier is an ad hoc annotation indicating that the field should be ignored during serialization. Java 5.0 has general purpose annotatons (aka metadata) allows you to define and use your own annotation type. The facility consists of a syntax for declaring annotation types, a syntax for annotating declarations, APIs for reading annotations, a class file representation for annotations, and an annotation processing tool.

Annotation do not have direct impact on program semantics, but they do affect the way programs are treated by tools and libraries, which can in turn affect the semantics of the running program. Annotations can be read from source files, class files, or reflectively at run time. Annotations complement javadoc tags. In general, if the markup is intended to affect or produce documentation, it should probably be a javadoc tag; otherwise, it should be an annotation.

Annotation type declaration:

Annotation type declarations are similar to interface declarations. An at-sign (@) precedes the interface keyword. Each method declaration defines the element of the annotation type, and method must not have any parameters or any throw clause. Return types are restricted to primitives, String, enum, annotations and array of the mentioned types. Method can also have default values.

Here is an illustration to declare annotation type.

package com.thetechhournals.annotation;

import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ChangeRequest
{
int    id();
String title();
String designer() default “[unassigned]“;
String status();    default “[unassigned]“;
}

The @interface in the code indicates that the interface itself is an annotation, It is required to be import java.lang.annotation package.

The next thing to be noted about the ChangeRequest annotation is @Retention(RetentionPolicy.RUNTIME) indicates that the @ChangeRequest is compiled into class file and made available to Java Virtual Machine at run time. This makes it possible for development tool to look for @ChangeRequest annotation through reflection at run time and to perform a specific task because the annotation was present in the code.

The other possible values for the @Retention annotation are:
  • The RetentionPolicy.SOURCE constant indicates that the annotation should be discarded by the compiler, and is usable by any development tools at coding time only.
  • The RetentionPolicy.CLASS constant indicates that the annotation is useful to the compiler, and should be retained in the .class file for use by the compiler at compile time.
Note: nless you are writing your own Java compiler, it is not possible to create your own useful compile-time annotations.

One more interesting part of the ChangeRequest annotation is @Target(ElementType.METHOD) indicates that the annotation should appear only on a method declaration but not on a class, a constructor, would generate a compiler error. It is possible to specify that an annotation appear on one or more elements within Java program, including on constructors, fields, local variables, method declarations, package declarations, parameter declarations; and class, interface, or enumeration declarations. Have look at below given example:

@Target({ElementType.CONSTRUCTOR,
ElementType.FIELD,
ElementType.METHOD,
ElementType.PACKAGE,
ElementType.TYPE})

How to use Java Annotation:

Once the annotation type is defined, you can use it to annotate declarations. An annotation is a special kind of modifier, and can be used anywhere that other modifiers (such as public, static, or final) can be used. By convention, annotations precede other modifiers. Annotations consist of an at-sign (@) followed by an annotation type and a parenthesized list of element-value pairs. The values must be compile-time constants. Here is a method declaration with an annotation corresponding to the annotation type declared above:

@ChangeRequest(
id    = 226724,
title = “Enable - Express shipping”,
designer = “S. Chandru”,
status = “Work in progress”
)
public boolean expressShipping(){…}

An annotation type with no elements is termed a marker annotation type, for example:

public @interface Basic{ }

It is permissible to omit the parentheses in marker annotations, as shown below:

@Basic
public class Shipping{ ... }

In annotations with a single element, the element should be named value, as shown below:

public @interface Copyright
{
    String value();
}

It is permissible to omit the element name and equals sign (=) in a single-element annotation whose element name is value, as shown below:

@Copyright("2009 The Tech Journals")
public class ShippingService{ ... }

How annotations works:

We will build small annotation-based MyAnnotation framework explain how annotation works. First let’s create a marker annotation type and should be run by the testing tool.

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation{ }

Note that the annotation type declaration is itself annotated. Such annotations are called meta-annotations. @Target(ElementType.METHOD) indicate that MyAnnotation should appear on methods and @Retention(RetentionPolicy.RUNTIME) make MyAnnotation available to JVM at run-time.

Here is sample program that uses the above defined annotation type.

package com.thetechjournals.annotation;

public class UsingAnnotation
{
@MyAnnotation
public static void use()
{
System.out.println(”I’m using annotations”);
}
public static void dontUse()
{
System.out.println(”I’m using annotations”);
}
}

and the testing tool:

import java.lang.reflect.*;

public class RunAnnotation
{
public static void main(String[] args) throws Exception
{
for (Method m : Class.forName(”com.thetechjournals.annotation.UsingAnnotation”).getMethods())
{
if (m.isAnnotationPresent(MyAnnotation.class))
{
System.out.println(”Annotated elements process in special way”);
m.invoke(null);
}
}
}
}

Using reflection we are dynamically loading UsingAnnotation class and iterates over all the methods of the class. Invoking each method that is annotated with the MyAnnotation annotation type. isAnnotationPresent( annotationType ) returns true if an annotation for the specified type is present on this element, else false. We can now process all the annotated elements in special way e.g., we can perform some operation before and after executing only annotated element.

Source and reference : Sun Official Site

S.Chandru Java , , ,