Decorative Programming using Annotations - Java
Home » Java, Tech Notes

Decorative Programming using Annotations

20 July 2009 No Comment

Annotation is not a new feature getting introduced in Java 5, but in this release Java is trying to explore the power of this feature. If we look at the open source product stack adapting to Java 5, then this is the feature what has changed most of the products considerably. It has begun a new era of decorative programming. In this article, it is assumed that you already have knowledge of Java, and can appreciate this article focusing on the concept of annotations, use of annotations etc.

Annotations Prior to Java 5:

As said above, annotations are not new to Java. We have used annotations in Java programs prior to Java 5. Just that the use was limited to Java doc comments and little bit more to deprecate a method. In Java doc also we used @ to identify annotations. Simple example below can remind you if at all you have forgot.

/**
 * Java doc example prior to Java 5
 * @author deepakgaikwad.net
 */
public class AnnotationsPriorToJava5 {

/**
 * Main Method
 * @param args input parameters
 */
	public static void main(String[] args) {

		System.out.println("Java Doc Example");
	}

}

In above code @author is an annotation. It is used to add author information to the java doc generated. This annotation is handled by the javadoc compiler only. For normal Java compiler it is just a comment.

What are Annotations or Metadata?

Annotations or Metadata feature is taken to new level in Java 5. Metadata means data about (other) data. E.g. in relational database where we have many tables containing business data, a query returning the data of table structure itself is a metadata query, and the query results are metadata. Annotations are also defining data about the underlying class structure. Prior to Java 5, @deprecated annotation told us that, any method having this annotation should no longer be used. In Java 5, there are many annotations which give additional information of the class structure as well as behavior. Annotation technology is based on a GOF (Gang Of Four) design pattern – decorator design pattern.

Decorator Design Pattern:

Attach additional responsibilities to an object dynamically.

Above definition clearly means changing objects and not classes. Programmer writes classes, but when the objects are created using these classes, the behavior is altered using a decoration technique. This decoration can be achieved at any time during the lifecycle of a class.

  • Compile: Compiler executes the decoration and generates the expected result.
  • Deployment: Container, in which the class is getting deployed, reads the deployment descriptor for the class and alters the behavior.
  • Runtime: Runtime values change the behavior of the class.

Java provides annotations that can control behavior of class at all three stages above.

Annotations Available in Java 5:

Java provides few built in annotations. Let us see what these annotations along with examples are wherever required.

@Override

It is used to indicate that the method decorated with this annotation overrides a super class method. This is a compile time check to prevent mistakes of writing additional method instead of overriding.

public class OverridesExample {

	@Override
	public void equals(){
		//body
	}
}

In above class, we have used the annotation Override to indicate that equals method overrides the super class (java.lang.Object) class equals method. This code will result in compilation error that – The method equals of Type OverridesExample must override a super class method. Change the code as shown below and the error will be resolved.

public class OverridesExample {

	@Override
	public boolean equals(Object obj1){
		//body
		return true;
	}
}

@Documented

This annotation indicates that a tool (may be javadoc or any other tool used to generate documentation) will document the code annotated using this. This will give a hint to the tool but will not make it mandatory to document, it is tool configuration that will finally decide whether the javadoc will be generated or not.

@Deprecated

Used to generate a warning indicating a programmer – this method/variable is deprecated. The programmer can avoid using this method and search for other alternatives.

@Inherited

It forces the annotation subclass to inherit the annotations from super class. E.g. suppose a super class method has @Documented annotation and the subclass method overrides this method. You can write @inherited annotation to tell that the @Documented annotation is available by default in subclass method.

@Retention(RetentionPolicy.CLASS)

It defines retention policy of annotation. There are three values of it controlling scope of the annotation details.

  • SOURCE: Discarded by compiler only
  • CLASS: Compiler retains but VM discards
  • RUNTIME: VM retains

@Target(ElementType.FIELD)

It is used to define where this annotation can be used. Applicable values can be Package, Method, Field etc.

Creating Custom Annotations:

Though Sun has provided very few ready annotations, but it has kept a room to develop custom annotations as required. With simple technique below, we can write our own annotations and use them. Here we require three classes to make it all work.

  • Annotation class
  • Class using this annotation

Implementation of the annotation

//MyAnnotation

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
	boolean permited();
}

//UsingMyAnnotation

public class UsingMyAnnotation {

	@MyAnnotation(permited=true)
	public void testAnnotationMethod(){
		AnnotationWork aw = new AnnotationWork();
		aw.makeItWork();
	}

	public static void main(String[] args){
		UsingMyAnnotation uma = new UsingMyAnnotation();
		uma.testAnnotationMethod();
	}
}

Using reflection we can go further to implement use of this annotation to make it work.

//AnnotationWork

import java.lang.reflect.Method;

public class AnnotationWork {

	public void makeItWork(){
		StackTraceElement ste[] = Thread.currentThread().getStackTrace();
		int count = 0;
		for(count = 0;count

Future with Annotations:

Annotations are mainly based on decorator design pattern, which is used to provide additional behavior to classes. In past few years, we have been decorating classes using declarative method. We used XMLs to declare the configurable behavior. Also we used this pattern and XMLs to configure the services required from application servers. The major disadvantage of this XML based configuration is the performance hit involved in XML reading and processing. Using annotations, it is going to be all Java processing and we may not need to depend on XMLs so much.

Examples of Application of Annotations:

After release of Java 5, there have been releases of many dependent technologies. The prime focus is usage of annotation to improve those technologies. Here are a couple examples.

  • EJB using annotation to inject EJB types and to control the application server services.
  • JPA having object relational mapping using annotation.
  • Hibernate having annotation based implementation of JPA

Summary:

Annotations have caused a major shift in declarative configuration of Java programs. It has also opened gates for new releases of open source and proprietary technologies to use annotations to improve performance of Java programs, and to improve productivity also. Though Java provides few ready annotations, the potential this technology has can bring major shifts in the future of Java technology.

Previous Next

 

More Related Posts in Java, Tech Notes

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.