Understanding @Target and ElementType
You'll learn: How to control exactly where your custom annotations can be applied using the @Target meta-annotation and ElementType values.
When you create a custom annotation, Java doesn't automatically restrict where it can be used. Can it go on classes? Methods? Fields? All of the above? The @Target meta-annotation lets you explicitly define these rules.
The @Target Meta-Annotation
@Target takes one or more ElementType enum constants as its value, specifying valid locations for your annotation:
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyMethodAnnotation {
String value();
}
Now @MyMethodAnnotation can only be applied to methods. Trying to use it on a class or field will cause a compile-time error.
Common ElementType Values
The ElementType enum provides specific locations:
TYPE— classes, interfaces, enumsFIELD— instance and static fieldsMETHOD— methodsPARAMETER— method or constructor parametersCONSTRUCTOR— constructorsLOCAL_VARIABLE— local variables (rare with RUNTIME retention)ANNOTATION_TYPE— other annotations (for meta-annotations)PACKAGE— package declarations
Multiple Targets
You can allow multiple locations by passing an array:
@Target({ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Validated {
// Can be applied to fields OR methods
}
Omitting @Target
If you don't specify @Target, your annotation can be applied anywhere — usually not what you want, as it reduces type safety and clarity.
Key Takeaway: Use @Target with appropriate ElementType values to precisely control where your custom annotation can be applied, preventing misuse and making your intent clear to other developers.