Wednesday, 27 April 2011

Java Annotation Types

Annotation can be classified in 2 ways :
  1. Based on what they are annotating
  2. Based on the number of arguments
Based on what they are annotating
There are two types of annotations available with JDK5:
  • Simple annotations: These are the basic types supplied with Tiger, which you can use to annotate your code only; you cannot use those to create a custom annotation type.
  • Meta annotations: These are the annotation types designed for annotating annotation-type declarations. Simply speaking, these are called the annotations-of-annotations.

Based on the number of arguments
There are three annotation types:


Marker
Marker type annotations have no elements, except the annotation name itself.

Example:
public @interface MyAnnotation {
}
Usage:
@MyAnnotation
public void mymethod() {
....
}

Single-Element
Single-element, or single-value type, annotations provide a single piece of data only. This can be represented with a data=value pair or, simply with the value (a shortcut syntax) only, within parenthesis.
Example:
public @interface MyAnnotation
{
String doSomething();
}
Usage:
@MyAnnotation ("What to do")
public void mymethod() {
....
}

Full-value or multi-value
Full-value type annotations have multiple data members. Therefore, you must use a full data=value parameter syntax for each member.
Example:
public @interface MyAnnotation {
String doSomething();
int count; String date();
}
Usage:
@MyAnnotation (doSomething="What to do", count=1,
date="09-09-2005")
public void mymethod() {
....
}

No comments:

Post a Comment