Java Annotation @Target
In Java, the @Target
annotation is used to specify the type of Java elements to which an annotation can be applied. It is used in the definition of custom annotations.
The @Target
annotation takes an array of ElementType
values as its argument. These values indicate the type of elements to which the annotation can be applied. The ElementType
enum contains constants for all the possible target elements, including:
ANNOTATION_TYPE
: The annotation can be applied to another annotation.CONSTRUCTOR
: The annotation can be applied to a constructor.FIELD
: The annotation can be applied to a field or property.LOCAL_VARIABLE
: The annotation can be applied to a local variable.METHOD
: The annotation can be applied to a method.PACKAGE
: The annotation can be applied to a package.PARAMETER
: The annotation can be applied to a parameter.TYPE
: The annotation can be applied to a class, interface, enumeration, or annotation type.
For example, if you define a custom annotation that can only be applied to methods, you would use @Target(ElementType.METHOD)
to specify this constraint.
Here's an example of a custom annotation with @Target
annotation applied to it:
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface MyCustomAnnotation { // ... }
In the example above, MyCustomAnnotation
can only be applied to methods due to the @Target(ElementType.METHOD)
annotation.