Monday, 9 May 2011

Annotating an annotations

When you start writing your own annotation types, the main purpose of your annotation types is to provide basic documentation. Also you write annotation types that are specific to a certain member type, or perhaps a certain set of member types. This requires you to supply some sort of metadata on your annotation type, so that the compiler can enforce the annotation’s intended functionality.

The most obvious meta-annotation is one that allows you to indicate which program elements can have annotations of the defined type.
Such meta-annotation is called Target. We have alread discussed @Target annotation here. You should know about another new class called ElementType. This enum defines the various program elements that an annotation type can target.

 

ElementType enum

package java.lang.annotation;

public enum ElementType {
TYPE, // Class, interface, or enum (but not annotation)
FIELD, // Field (including enumerated values)
METHOD, // Method (does not include constructors)
PARAMETER, // Method parameter
CONSTRUCTOR, // Constructor
LOCAL_VARIABLE, // Local variable or catch clause
ANNOTATION_TYPE, // Annotation Types (meta-annotations)
PACKAGE // Java package
}


The enumerated values in exampel above are obvious. When you use the Target meta-annotation, you supply it at least one of these enumerated values and indicate
which program elements the annotated annotation can target. Now we have to use target annotation.

 

Using Target annotation to annotate your annotation


package com.vaani.annotations.target; 
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;

// Using the Target meta-annotation
/**
* Annotation type to indicate a task still needs to be completed
*/
@Target({ElementType.TYPE,
ElementType.METHOD,
ElementType.CONSTRUCTOR,
ElementType.ANNOTATION_TYPE})
public @interface TODO {
String value();
}

Now the Java compiler will apply TODO only to types, methods, constructors, and other annotation types.
This helps you ensure that nobody else uses your custom annotation type and misapplies it.


No comments:

Post a Comment