Java Annotation Targets: @Target and ElementType Explained
Java annotation targets decide where an annotation may be written: on a class, a method, a field, a parameter, a type argument and so on. You set them with the @Target meta-annotation and the constants of the ElementType enum.
Targets protect your annotations from misuse. If @Audited only makes sense on methods, @Target(ElementType.METHOD) makes the compiler reject it anywhere else. In Java Custom Annotations you used @Target briefly; this lesson covers every target in depth and ends with a small web router that uses three different targets together.
Java Annotation Targets Syntax
@Target takes one ElementType or an array of them. It is placed on the annotation type declaration, next to @Retention.
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) // one target
@interface OneTarget { }
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER}) // several targets
@interface ManyTargets { }
Note:
@Targetis itself an annotation fromjava.lang.annotation, covered in Java Built-in Annotations. It only affects where the annotation compiles;@Retentionstill decides whether you can read it at runtime.
All ElementType Constants
| ElementType | Where the annotation may appear | Example |
|---|---|---|
TYPE | Class, interface, enum, record, annotation type | @Entity class User { } |
FIELD | Field, including enum constants | @Column private String name; |
METHOD | Method | @Test void login() { } |
PARAMETER | Method or constructor parameter | void find(@PathParam("id") int id) |
CONSTRUCTOR | Constructor | @Inject public Service() { } |
LOCAL_VARIABLE | Local variable | @Todo("x") int count = 0; |
ANNOTATION_TYPE | Another annotation type (meta-annotation) | @Stereotype @interface Service { } |
PACKAGE | Package declaration in package-info.java | @Deprecated package com.app.old; |
TYPE_PARAMETER | Generic type parameter declaration | class Box<@Entity T> { } |
TYPE_USE | Any use of a type | List<@NonEmpty String> |
MODULE | Module declaration in module-info.java | @Deprecated module com.app { } |
RECORD_COMPONENT | Record component | record Customer(@Sensitive String phone) { } |
The first eight are declaration contexts: they annotate something you declare. TYPE_USE is a type context: it annotates the type itself wherever the type is written.
Restricting an Annotation to One Target
The most common case is a single target. This @Audited annotation is only valid on methods:
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) // allowed on methods only
@interface Audited { }
public class SingleTarget {
@Audited
public void transferFunds() { }
public static void main(String[] args) throws NoSuchMethodException {
boolean audited = SingleTarget.class
.getMethod("transferFunds")
.isAnnotationPresent(Audited.class);
System.out.println("transferFunds audited? " + audited);
}
}
Output:
transferFunds audited? true
How it works:
@Target(ElementType.METHOD)tells the compiler that@Auditedbelongs on methods.getMethod("transferFunds")finds the public method, andisAnnotationPresentconfirms the annotation is there at runtime.
What Happens With the Wrong Target
Now put the same annotation on a field:
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@interface Audited { }
public class WrongTarget {
@Audited // a field is not a method
private double balance;
}
WrongTarget.java:9: error: annotation interface not applicable to this kind of declaration
@Audited // a field is not a method
^
1 error
The program never compiles, so the mistake cannot reach production. This is the main reason to always declare a target.
Allowing Multiple Annotation Targets
Pass an array to allow several kinds of declarations. A @Since annotation that records the version a feature arrived in fits classes, fields, constructors and methods:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.CONSTRUCTOR})
@interface Since {
String value();
}
@Since("1.0")
public class MultiTarget {
@Since("1.2")
private String couponCode;
@Since("1.1")
public MultiTarget() { }
@Since("2.0")
public void applyCoupon() { }
public static void main(String[] args) throws ReflectiveOperationException {
Class<MultiTarget> type = MultiTarget.class;
Field field = type.getDeclaredField("couponCode");
Constructor<MultiTarget> constructor = type.getConstructor();
Method method = type.getMethod("applyCoupon");
System.out.println("class -> " + type.getAnnotation(Since.class).value());
System.out.println("field -> " + field.getAnnotation(Since.class).value());
System.out.println("constructor -> " + constructor.getAnnotation(Since.class).value());
System.out.println("method -> " + method.getAnnotation(Since.class).value());
}
}
Output:
class -> 1.0
field -> 1.2
constructor -> 1.1
method -> 2.0
How it works:
- The array
{TYPE, FIELD, METHOD, CONSTRUCTOR}lists every allowed place. Putting@Sinceon a parameter would still fail to compile. - Each reflective object (
Class,Field,Constructor,Method) has its owngetAnnotationmethod, so you read the value from exactly the element you annotated.
When @Target Is Missing
An annotation type without @Target is allowed in all declaration contexts but in no type contexts:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.List;
@Retention(RetentionPolicy.RUNTIME)
@interface Reviewed { } // no @Target
@Reviewed
public class NoTarget<@Reviewed T> { // class and type parameter: OK
@Reviewed private int count; // field: OK
@Reviewed public NoTarget() { } // constructor: OK
@Reviewed void save(@Reviewed String name) { // method and parameter: OK
@Reviewed int retries = 3; // local variable: OK
}
List<@Reviewed String> names; // type use: NOT allowed
}
NoTarget.java:19: error: annotation @Reviewed not applicable in this type context
List<@Reviewed String> names; // type use: NOT allowed
^
1 error
How it works:
- Every declaration in the class accepts
@Reviewed, because no@Targetmeans "any declaration". List<@Reviewed String>annotates a use of the typeString, not a declaration, so it needsElementType.TYPE_USEexplicitly.
Note: Relying on the default makes your annotation too permissive. Declare
@Targeteven when you want many contexts, so readers see the intent and the compiler catches mistakes.
LOCAL_VARIABLE Target
Local variable annotations compile fine, but they are never stored in a way reflection can read, even with RUNTIME retention. They are useful for the compiler, annotation processors and IDE tools only.
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.util.Arrays;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.LOCAL_VARIABLE})
@interface Todo {
String value();
}
public class LocalVar {
@Todo("add caching")
static int lookupPrice(String sku) {
@Todo("read from database") int price = 499;
return price;
}
public static void main(String[] args) throws NoSuchMethodException {
Method method = LocalVar.class.getDeclaredMethod("lookupPrice", String.class);
System.out.println("On method: " + Arrays.toString(method.getAnnotations()));
System.out.println("Price: " + lookupPrice("JAVA-101"));
}
}
Output:
On method: [@Todo("add caching")]
Price: 499
How it works:
- The method annotation is visible because methods keep
RUNTIMEannotations in the class file. - The local variable annotation
@Todo("read from database")compiles, but there is no reflection API for local variables, so it never shows up at runtime.
TYPE_USE and TYPE_PARAMETER Targets
TYPE_PARAMETER annotates the declaration of a generic parameter such as T. TYPE_USE is broader: it can go on any written type, including generic arguments, casts, new expressions, throws clauses and array element types. Null-checking tools such as the Checker Framework use TYPE_USE for annotations like @NonNull.
| Code | Annotation sits on |
|---|---|
List<@NonEmpty String> tags; | The type argument String |
(@NonEmpty Object) value | The cast type |
new @NonEmpty ArrayList<>() | The created type |
String @NonEmpty [] names; | The array type |
class Repository<@Entity T> | The type parameter T (TYPE_PARAMETER) |
Reading type-use annotations requires the getAnnotatedType() family of methods, not getAnnotation():
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.AnnotatedParameterizedType;
import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Field;
import java.util.List;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE_USE)
@interface NonEmpty { }
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE_PARAMETER)
@interface Entity { }
class Repository<@Entity T> { }
public class TypeUse {
// the annotation sits on the type argument, not on the field
List<@NonEmpty String> tags;
public static void main(String[] args) throws Exception {
Object tagsList = (@NonEmpty Object) List.of("java"); // cast: TYPE_USE allowed
System.out.println("Cast worked: " + tagsList);
Field field = TypeUse.class.getDeclaredField("tags");
System.out.println("Field annotations: " + field.getAnnotations().length);
AnnotatedParameterizedType listType = (AnnotatedParameterizedType) field.getAnnotatedType();
AnnotatedType elementType = listType.getAnnotatedActualTypeArguments()[0];
System.out.println("Element type: " + elementType.getType().getTypeName());
System.out.println("Has @NonEmpty: " + elementType.isAnnotationPresent(NonEmpty.class));
var typeParameter = Repository.class.getTypeParameters()[0];
System.out.println("Type parameter " + typeParameter.getName()
+ " has @Entity: " + typeParameter.isAnnotationPresent(Entity.class));
}
}
Output:
Cast worked: [java]
Field annotations: 0
Element type: java.lang.String
Has @NonEmpty: true
Type parameter T has @Entity: true
How it works:
field.getAnnotations()returns nothing, because@NonEmptybelongs to the type argumentString, not to the fieldtags.field.getAnnotatedType()returns the full annotated typeList<@NonEmpty String>. Casting it toAnnotatedParameterizedTypegives access to the annotated type arguments, where@NonEmptylives.getTypeParameters()returnsTypeVariableobjects, which also implementAnnotatedElement, soisAnnotationPresentworks onTdirectly.
RECORD_COMPONENT Target and Annotation Propagation
An annotation on a record component is copied by the compiler to every generated member whose kind matches its @Target: the component itself, the private field, the accessor method and the canonical constructor parameter.
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.RECORD_COMPONENT)
@interface Sensitive { }
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
@interface Masked { }
record Customer(String name, @Sensitive @Masked String phone) { }
public class RecordTarget {
public static void main(String[] args) throws Exception {
var component = Customer.class.getRecordComponents()[1];
var field = Customer.class.getDeclaredField("phone");
var accessor = Customer.class.getMethod("phone");
System.out.println("component " + component.getName()
+ ": @Sensitive=" + component.isAnnotationPresent(Sensitive.class)
+ ", @Masked=" + component.isAnnotationPresent(Masked.class));
System.out.println("field " + field.getName()
+ ": @Sensitive=" + field.isAnnotationPresent(Sensitive.class)
+ ", @Masked=" + field.isAnnotationPresent(Masked.class));
System.out.println("accessor " + accessor.getName()
+ "(): @Sensitive=" + accessor.isAnnotationPresent(Sensitive.class)
+ ", @Masked=" + accessor.isAnnotationPresent(Masked.class));
}
}
Output:
component phone: @Sensitive=true, @Masked=false
field phone: @Sensitive=false, @Masked=true
accessor phone(): @Sensitive=false, @Masked=true
How it works:
@Sensitivetargets onlyRECORD_COMPONENT, so it stays on the component and is not copied anywhere else.@MaskedtargetsFIELDandMETHOD, so the compiler copies it to the generatedprivate final String phonefield and thephone()accessor, but not to the component.- This is how libraries such as Jackson or Jakarta Validation see annotations written on records: they read the field or accessor, so those annotations need
FIELDorMETHODin their target list.
ANNOTATION_TYPE Target: Building Meta-Annotations
ANNOTATION_TYPE lets an annotation be placed on other annotation types. This is how you build a family of related annotations. Spring's @Service and @Repository are both marked with @Component this way.
import java.lang.annotation.Annotation;
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.ANNOTATION_TYPE) // only on other annotations
@interface Stereotype {
String value();
}
@Stereotype("service")
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface Service { }
@Stereotype("repository")
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface Repository { }
@Service
class PaymentService { }
@Repository
class OrderRepository { }
class PlainHelper { }
public class MetaAnnotationDemo {
static String describe(Class<?> type) {
for (Annotation annotation : type.getAnnotations()) {
Stereotype stereotype = annotation.annotationType().getAnnotation(Stereotype.class);
if (stereotype != null) {
return type.getSimpleName() + " is a " + stereotype.value()
+ " (via @" + annotation.annotationType().getSimpleName() + ")";
}
}
return type.getSimpleName() + " is not a managed component";
}
public static void main(String[] args) {
System.out.println(describe(PaymentService.class));
System.out.println(describe(OrderRepository.class));
System.out.println(describe(PlainHelper.class));
}
}
Output:
PaymentService is a service (via @Service)
OrderRepository is a repository (via @Repository)
PlainHelper is not a managed component
How it works:
@Stereotypecan only be written on annotation types. Putting it onPaymentServicedirectly would not compile.annotation.annotationType()returns theClassof the annotation, for exampleService.class. Asking that class for@Stereotypereveals the meta-annotation.- The scanner never mentions
@Serviceor@Repositoryby name, so new stereotypes work without changing it.
PACKAGE and MODULE Targets
These two targets are written in special files instead of normal classes:
// file: com/gocourse/legacy/package-info.java
@Deprecated(since = "3.0")
package com.gocourse.legacy;
// file: module-info.java
@Deprecated(forRemoval = true)
module com.gocourse.reports { }
You read them with SomeClass.class.getPackage().getAnnotation(...) and SomeClass.class.getModule().getAnnotation(...). A custom annotation needs @Target(ElementType.PACKAGE) or @Target(ElementType.MODULE) to be allowed there.
Real-World Example: A Mini Web Router With Three Targets
Web frameworks such as Spring MVC and Jakarta REST combine annotation targets: a class-level annotation for the base path, method-level annotations for each route and parameter-level annotations for values from the URL. This example builds a small router that does the same.
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
// ---------- annotations: one per target ----------
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface Controller {
String value(); // base path
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface Get {
String value(); // path after the base
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
@interface PathParam {
String value(); // name of the {placeholder}
}
// ---------- a controller written by the "user" ----------
@Controller("/courses")
class CourseController {
@Get("")
public String listCourses() {
return "Java, Python, Go";
}
@Get("/{id}")
public String findCourse(@PathParam("id") int courseId) {
return "Course #" + courseId;
}
@Get("/{id}/lessons/{lesson}")
public String findLesson(@PathParam("id") int courseId, @PathParam("lesson") String lessonSlug) {
return "Course #" + courseId + ", lesson '" + lessonSlug + "'";
}
}
// ---------- the "framework" ----------
class Router {
private record Route(String[] segments, Method handler, Object controller) { }
private final List<Route> routes = new ArrayList<>();
void register(Object controller) {
Class<?> type = controller.getClass();
Controller base = type.getAnnotation(Controller.class);
if (base == null) {
throw new IllegalArgumentException(type.getSimpleName() + " is not a @Controller");
}
Method[] methods = type.getDeclaredMethods();
Arrays.sort(methods, Comparator.comparing(Method::getName)); // stable order
for (Method method : methods) {
Get get = method.getAnnotation(Get.class);
if (get != null) {
String fullPath = base.value() + get.value();
routes.add(new Route(fullPath.substring(1).split("/"), method, controller));
System.out.println("Mapped GET " + fullPath + " -> " + method.getName());
}
}
}
String dispatch(String path) throws ReflectiveOperationException {
String[] requestSegments = path.substring(1).split("/");
for (Route route : routes) {
Map<String, String> pathValues = match(route.segments(), requestSegments);
if (pathValues == null) {
continue;
}
Parameter[] parameters = route.handler().getParameters();
Object[] arguments = new Object[parameters.length];
for (int i = 0; i < parameters.length; i++) {
String name = parameters[i].getAnnotation(PathParam.class).value();
String rawValue = pathValues.get(name);
arguments[i] = parameters[i].getType() == int.class ? Integer.parseInt(rawValue) : rawValue;
}
return (String) route.handler().invoke(route.controller(), arguments);
}
return "404 Not Found";
}
private static Map<String, String> match(String[] pattern, String[] actual) {
if (pattern.length != actual.length) {
return null;
}
Map<String, String> values = new HashMap<>();
for (int i = 0; i < pattern.length; i++) {
if (pattern[i].startsWith("{")) {
values.put(pattern[i].substring(1, pattern[i].length() - 1), actual[i]);
} else if (!pattern[i].equals(actual[i])) {
return null;
}
}
return values;
}
}
public class MiniRouter {
public static void main(String[] args) throws ReflectiveOperationException {
Router router = new Router();
router.register(new CourseController());
System.out.println();
List<String> requests = List.of(
"/courses",
"/courses/42",
"/courses/42/lessons/annotation-targets",
"/students");
for (String path : requests) {
System.out.println("GET " + path + " => " + router.dispatch(path));
}
}
}
Output:
Mapped GET /courses/{id} -> findCourse
Mapped GET /courses/{id}/lessons/{lesson} -> findLesson
Mapped GET /courses -> listCourses
GET /courses => Java, Python, Go
GET /courses/42 => Course #42
GET /courses/42/lessons/annotation-targets => Course #42, lesson 'annotation-targets'
GET /students => 404 Not Found
How it works:
- Three targets, three jobs.
@Controller(TYPE) gives the base path,@Get(METHOD) maps each handler and@PathParam(PARAMETER) names the URL value each argument receives. Writing@PathParamon a method would not compile, so the user cannot mix them up. - Registration.
registerreads@Controllerfrom the class, then every@Getmethod, and joins the two paths./courses+/{id}becomes/courses/{id}. Methods are sorted by name becausegetDeclaredMethods()has no guaranteed order. - Matching.
matchcompares the request path segment by segment. A segment in braces, such as{id}, captures the request value under the nameid. - Binding parameters. For each method parameter,
getAnnotation(PathParam.class)gives the placeholder name. The value is converted tointwhen the parameter type isint, sofindCoursereceives the number42, not the text"42". - Invoking.
Method.invokecalls the handler on the controller object. Howinvokeand other reflective calls work in detail is the subject of the next lesson, Java Reflection API. - No match.
/studentsmatches no route, sodispatchreturns404 Not Found.