View RSS Feed

My Java Tips

Annotating an annotation

Rate this Entry
by , 10-31-2011 at 06:32 PM (1542 Views)
I will briefly write about annotating annotations. You should have good idea about the set of predefined annotation types we have seen in the last few posts.

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. You should know about another new class called ElementType. This enum defines the various program elements that an annotation type can target.

I will now present an example that shows the ElementType enum :

Java Code:
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 example 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.

Its time to show Target in action:

Java Code:
package com.domain.tiger.a;

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
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.

Hope this helps.

Submit "Annotating an annotation" to Facebook Submit "Annotating an annotation" to Digg Submit "Annotating an annotation" to Submit "Annotating an annotation" to StumbleUpon Submit "Annotating an annotation" to Google

Tags: None Add / Edit Tags