VOOZH about

URL: https://www.geeksforgeeks.org/java/java-target-annotations/

⇱ Java - @Target Annotations - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java - @Target Annotations

Last Updated : 23 Jul, 2025

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 
ConstructorConstructor
Local_Variable Local variable 
Annotation_Type Annotation Type 
Package PACKAGE
Type_ParameterType 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 


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


 

Comment
Article Tags:
Article Tags: