Java 1.5 Tiger A Developers Notebook [Electronic resources]

David Flanagan, Brett McLaughlin

نسخه متنی -صفحه : 131/ 69
نمايش فراداده

6.7 Defining an Annotation Type's Target

The first meta-annotation, Target, is used to specify which program elements are allowed as targets for the defined annotation. This prevents misuse of an annotation, and is strongly recommended as a sanity check for all your custom annotations.

6.7.1 How do I do that?

Target should be used in the lines directly preceding the annotation definition:

    @Target({ElementType.TYPE,
ElementType.METHOD,
ElementType.CONSTRUCTOR,
ElementType.ANNOTATION_TYPE})
public @interface TODO {

Target takes a single member whose type is an array of values, each of which should be an enumerated value from the java.lang.annotation. ElementType enum.

This enum defines the various program elements allowed as targets of an annotation type, and is shown in Example 6-8.

NOTE

The actual parameter type in Target is ElementType[].

Example 6-8. The 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
}

You'll need to remember to import both Target and ElementType in your code. Example 6-9 shows an updated version of the TODO annotation type, first defined back in Example 6-5.

Example 6-9. Annotating an annotation
package com.oreilly.tiger.ch06;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
/**
* 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( );
}

It's interesting to note the Target meta-annotation is used on itself (shown in Example 6-10), indicating that it can only be used as a metaannotation.

Example 6-10. Source code for Target annotation type
package java.lang.annotation;
@Documented
@Retention(RetentionPolicy.RUNTIME);
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
ElementType[] value( );
}

6.7.2 What about...

...annotation types that work for all program elements? In these cases, you don't need to use Target at all.