Open In App

Java – @Target Annotations

Last Updated : 23 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Annotations in java are used to associate metadata to program elements like classes, methods, instance variables, etc. There are mainly three types of annotations in java: Marker Annotation (without any methods), Single-Valued Annotation (with a single method), and Multi-Valued Annotation (with more than one method). @Target annotation is a meta-annotation, i.e., it can only be used to annotate other annotations. It takes ElementType enumeration as its only argument. ElementType enumeration is a constant which specifies the type of the program element declaration (class, interface, constructor, etc.) to which the annotation can be applied. If we apply the @Target annotation with some ElementType as an annotation to a custom annotation name CustomAnnotation, then @CustomAnnotation can only be used to annotate those specific elements types otherwise we will get an error.  

The table below shows the element types, and the element declaration that can be annotated are mentioned below as follows:

Element Type  Element to be Annotated 
Type  Class, interface or enumeration
Field  Field
Method  Method 
Constructor Constructor
Local_Variable  Local variable 
Annotation_Type  Annotation Type 
Package  PACKAGE
Type_Parameter Type Parameter 
Parameter  Formal Parameter 

In order to use @Target annotation follow the below syntax as follows: 

Syntax:

@Target(ElementType.TYPE)
@interface CustomAnnotation {}

In the code sample mentioned above, we have created a custom annotation annotated using @Target annotation. Since we have used ElementType as TYPE, therefore, the custom annotation can only annotate a class, enumeration, or interface. We can also create a custom annotation that can be applied to multiple elements by giving a braces-delimited list of element types as an argument to @Target annotation as shown below.

Syntax:

@Target({ElementType.METHOD, ElementType.PACKAGE})
@interface CustomAnnotation {}

The custom annotation created above can be used to annotate a method or a package. The code mentioned below shows how we can use @Target annotation. We have created two custom annotations: one which can be applied to a single element type and one which can be applied to multiple element types. Then we apply these annotations to our class and method, and finally, we print these annotations by fetching them.

Implementation:

Example 

Java




// Java program to Illustrate Targeted Annotations
  
// Importing required classes from java.lang package  
import java.lang.annotation.*;
  
// Creating a custom annotation with target
// as TYPE which means it can annotate a class,
// enumeration, or interface
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
  
// Class Annotation
@interface ClassAnnotation
{
    String value() default "Can annotate a class";
}
  
// Creating custom annotation with
// target as multiple Element types as parameters
// which means it can annotate various Elements
@Target({ ElementType.METHOD, ElementType.TYPE,
          ElementType.ANNOTATION_TYPE,
          ElementType.CONSTRUCTOR })
@Retention(RetentionPolicy.RUNTIME)
@interface MultipleElementTypeAnnotation
{
  
    String value() default "Can annotate a class, method, "
        + "annotation, or constructor";
}
  
// Class to demonstrate the use of custom
// created annotations
@ClassAnnotation
  
// Main class
// TargetAnnotationDemo
public class GFG {
  
    @MultipleElementTypeAnnotation public void myMethod() {}
  
    // Main drive method
    public static void main(String[] args) throws Exception
    {
        GFG obj = new GFG();
  
        // Accessing the annotations used to annotate the
        // class and storing them in an array of Annotation
        // type since only one annotation is used to
        // annotate our class therefore we print a[0]
        Annotation a[] = obj.getClass().getAnnotations();
  
        System.out.println(a[0]);
  
        // Accessing the annotations used to annotate the
        // method and storing them in an array of Annotation
        // type
        Class<?> className = Class.forName("GFG");
        Annotation b[] = className.getMethod("myMethod")
                             .getAnnotations();
  
        System.out.println(b[0]);
    }
}


Output

@ClassAnnotation(value="Can annotate a class")
@MultipleElementTypeAnnotation(value="Can annotate a class, method, annotation, or constructor")

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads