Monday, June 16, 2008

What are Annotations in Java? What are they used for?


Annotations in Java

These are pieces of code which don't have any direct impact on the execution of the code, instead they provide additional data about the program (and not a part of the program) to either the compiler or the run-time system. This data is used by the compiler or the run time system to do a variety of things - generation of additional code, XML files, suppress warnings, errors, etc. Annotations are sometimes preferred on comments as they make the documentation of a program quite flexible. We can even define annotation types, the way we define classes. This encourages code re-usability and makes the code more readable and maintainable. Annotations can be applied to every element of a Java program including classes, fields, methods, code blocks, etc. For generation of auxiliary code, XML files, etc., We may write annotation processors, which will read annotations specified in a Java program and they will take corresponding actions based on the specified annotation values. Most of the annotations are processed at the compile time only, but we may make annotation information available to the run time system if we want.

JDK 5.0 uses a tool called 'apt' for annotation processing whereas JDK 6.0 this feature is in-built in the Java Compiler itself.

Example: Sample Annotations in Java

@Author(
Name = "Geek"
Date = "6/16/2008")
class ClassA{
...

@SuppressWarnings("unchecked")
public int methodName(){
...
}
...

@Override
public void overridenMethod(){
...
}

}

Notice that an annotation may have named or unnamed elements and in case there are no elements, we may skip the parentheses as well.

Uses of Annotations in Java

  • Providing information to the Compiler - an annotation used for conveying some information to the compiler may help the compiler to either suppress warnings, detect errors, etc. Example of such annotations are: @SuppressWarnings(value = "some value"), @Override, @Deprecated
  • Providing information to the tools - an annotation used for this purpose may help various software tools to generate code, XML files, etc.
  • Providing inforamtion to the Runtime System - certain annotations convey information to the run time system to either guide the direction of the execution or to just notify something. Annotation information is made available to the run time system by using another annotation type called '@Retention(RetentionPolicy.RUNTINE)'. We just need to precede the annotation which we want to make available at run time by this annotation.

Specification-defined Annotation Types

There are three annotation types, which have been defined by the Java Language Specification. These are:- @Deprecated, @Override, @SuppressWarnings. It's quite obvious to understand what these annotation types are used for.



Share/Save/Bookmark


No comments: