Monday, 23 June 2014

Java : ElementType

ElementType is enum type. These constants are used in java.lang.annotation.Target meta-annotations to specify where it is legal to write annotations of a given type.

The syntactic locations where annotations may appear are split into declaration contexts , where annotations apply to declarations, and type contexts , where annotations apply to types used in declarations and expressions.

The constants ANNOTATION_TYPE , CONSTRUCTOR , FIELD , LOCAL_VARIABLE , METHOD , PACKAGE , PARAMETER , TYPE , and TYPE_PARAMETER correspond to the declaration contexts.

The constant TYPE_USE corresponds to the type contexts in, as well as to two declaration contexts: type declarations (including annotation type declarations) and type parameter declarations.

Constant Description
ANNOTATION_TYPE Specifies given Annotation can be applied to an annotation type.
CONSTRUCTOR Specifies given Annotation can be applied to construtor.
FIELD Specifies given Annotation can be applied to field declarations including enum constants.
LOCAL_VARIABLE Specifies given Annotation can be applied to local variables including variables in for loop and resource variables of try with resource statement).
METHOD Specifies given Annotation can be applied to method.
PACKAGE Specifies given Annotation can be applied to package.
PARAMETER Specifies given Annotation can be applied to formal and exception parameter.
TYPE Specifies given Annotation can be applied to class, interface, enum and Annotations.
TYPE_PARAMETER Specifies given Annotation can be applied to generic classes, interfaces, methods and constructors.
TYPE_USE Applicable for all 16 type contexts

import java.lang.annotation.*;

@Target (value = {ElementType.FIELD, ElementType.CONSTRUCTOR})
@interface DocumentMe{

}

We can apply Annotation DocumentMe to any field and constructors of class. But if you tries to apply it to any thing other than field and constructor, compiler throws error.

class TargetTest{
 @DocumentMe
 int field1;
 
 @DocumentMe
 TargetTest(){
 
 }
 
 @DocumentMe
 int method1(){
 
 }
}

When you tries to compile the above program, compiler throws below error. Since DocumentMe can't be applied to methods.

TargetTest.java:10: error: annotation type not applicable to this kind of declar
ation
        @DocumentMe
        ^
1 error





                                                             Home

No comments:

Post a Comment