Friday 27 June 2014

@Target

@Target annotation marks another annotation to restrict what kind of Java elements the annotation can be applied to.

Lets see it by an Example.

import java.lang.annotation.*;

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

}

To Know about ElementType read the below link.

We can apply Annotation DocumentMe to any field and constructors of a 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

1. It is a compile-time error if the same enum constant appears more than once in the value element of an annotation of type java.lang.annotation.Target.



 
Prevoius                                                 Next                                                 Home

No comments:

Post a Comment