The @Target
annotation in Java is a meta-annotation that is used to specify the types of elements to which an annotation can be applied. It is part of the Java Annotation API and allows you to restrict the usage of your custom annotations to specific program elements like classes, methods, fields, etc. In this tutorial, we’ll explore the @Target
annotation with simple examples.
Basic Syntax of @Target
The @Target
annotation takes an array of ElementType
constants as its value. Each constant represents a type of program element to which the annotation can be applied. The possible ElementType
constants include:
ElementType.ANNOTATION_TYPE
: Annotation type declaration.ElementType.CONSTRUCTOR
: Constructor declaration.ElementType.FIELD
: Field declaration.ElementType.LOCAL_VARIABLE
: Local variable declaration.ElementType.METHOD
: Method declaration.ElementType.PACKAGE
: Package declaration.ElementType.PARAMETER
: Parameter declaration.ElementType.TYPE
: Class, interface (including annotation type), or enum declaration.
Here’s an example of how to use @Target
:
In this example, the @MyAnnotation
annotation can only be applied to class/interface declarations (ElementType.TYPE
) and method declarations (ElementType.METHOD
).
Example: Creating a Custom Annotation with @Target
Let’s create a simple custom annotation called @MethodInfo
and use @Target
to specify where it can be applied.
In this example:
- The
@MethodInfo
annotation can only be applied to methods (ElementType.METHOD
). - The
@Retention(RetentionPolicy.RUNTIME)
annotation is included to indicate that the annotation information should be retained at runtime.
Now, let’s use the @MethodInfo
annotation in a class:
Here, we’ve applied the @MethodInfo
annotation to the myMethod
method. The annotation specifies details such as the author, date, revision, and comments related to the method.
Conclusion
The @Target
annotation is a powerful tool for custom annotation developers to specify where their annotations can be used within Java code. By using @Target
, you can enforce constraints on the types of program elements to which your annotations can be applied, providing a more controlled and meaningful usage of your annotations. Understanding and utilizing @Target
is essential for creating effective and well-designed custom annotations in Java.