Meta Annotation which is also called as Annotation of Annotation. This is of four types:
- Target
- Retention
- Documented
- Inherited
The Target Annotation
The target annotation indicates the targeted elements of a class in which the annotation type will be applicable. It contains the following enumerated types as its value:
- @Target(ElementType.TYPE)—can be applied to any element of a class
- @Target(ElementType.FIELD)—can be applied to a field or property
- @Target(ElementType.METHOD)—can be applied to a method level annotation
- @Target(ElementType.LOCAL_VARIABLE)—can be applied to local variables
- @Target(ElementType.PARAMETER)—can be applied to the parameters of a method
- @Target(ElementType.CONSTRUCTOR)—can be applied to constructors
- @Target(ElementType.ANNOTATION_TYPE)—indicates that the declared type itself is an annotation type
The @Target(ElementType.METHOD) indicates that this annotation type can be used to annotate only at the method levels.
1 2 3 4 5 6 7 8 9 |
package www.technicaljungle.com; import java.lang.annotation.ElementType; import java.lang.annotation.Target; @Target(ElementType.METHOD) public @interface TargetAnnotationInterface { String doSomething(); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package www.technicaljungle.com; public class TargetAnnotationSample{ public static void main(String []args) { new TargetAnnotationSample().doSomething(); } String str = null; @TargetAnnotationInterface(doSomething = "Hello Techy ") public void doSomething() { System.out.println("www.TechnicalJungle.com"); } } |
Above code will work fine. Because annotation type was for method level.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package www.technicaljungle.com; public class TargetAnnotationSample{ public static void main(String []args) { new TargetAnnotationSample().doSomething(); } //Since below line should be before method not before variable. // So compile time error is expected. @TargetAnnotationInterface(doSomething = "Hello Techy ") String str = null; public void doSomething() { System.out.println("www.TechnicalJungle.com"); } } |
1 |
Compile time error: The annotation @TargetAnnotationInterface is disallowed for this location. |
Above code will not work fine. Because annotation type was for method level and string variable has been added between target annotation and method.
@Target(ElementType.TYPE)
1 2 3 4 5 6 7 8 9 10 |
package www.technicaljungle.com; import java.lang.annotation.ElementType; import java.lang.annotation.Target; @Target(ElementType.TYPE) public @interface TargetAnnotationInterface { String doSomething(); int count = 10; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package www.technicaljungle.com; @TargetAnnotationInterface(doSomething = "Welcome") public class TargetAnnotationSample{ public static void main(String []args) { new TargetAnnotationSample().doSomething(); } public void doSomething() { System.out.println("www.TechnicalJungle.com"); } } |
1 |
Output: www.TechnicalJungle.com |
@Annotations