Annotations
An annotation attaches information to code: a class, method, field, parameter or type. The compiler reads some of them, annotation processors read others while compiling, and frameworks read many at run time to decide how to treat your code. This page explains where annotations are stored and what an annotation object is, then uses the built-ins, defines new ones, builds a small column mapper and validator, shows @Inherited and @Repeatable, and runs an annotation processor inside javac.
Contents
What an annotation is and where it lives The built-in annotations Defining and reading your own annotations Annotation objects, defaults and @Inherited An annotation-driven validator, and the cost of lookups Repeatable annotations Processing annotations at compile time Choosing a retention and a reader
What an annotation is and where it lives
An annotation (Java 5, JSR 175) is a marker such as @Override@Column(name = "email")@Retention
: discarded by the compiler. Only the compiler itself and annotation processors see it.SOURCE and@Override work this way.@SuppressWarnings , the default: written into the class file but not loaded at run time. Bytecode tools can read it; reflection cannot.CLASS : written into the class file in theRUNTIME attribute and available through reflection. Frameworks such as JPA, Spring and JUnit rely on this.RuntimeVisibleAnnotations
An annotation type is declared with @interfaceStringClass
| Annotation | Since | Read by | Purpose |
|---|---|---|---|
@Override | Java 5 | Compiler | Fail if the method does not override or implement anything |
@Deprecated | Java 5; sinceforRemoval | Compiler, tools, reflection | Warn users of an API that is going away |
@SuppressWarnings | Java 5 | Compiler | Silence named warnings in one declaration |
@SafeVarargs | Java 7 | Compiler | Promise that a generic varargs method is safe |
@FunctionalInterface | Java 8 | Compiler | Fail unless the interface has exactly one abstract method |
@Retention@Target@Documented@Inherited | Java 5 | Compiler, reflection | Meta-annotations that configure annotation types |
@Repeatable | Java 8 | Compiler | Allow the same annotation more than once on an element |
Java 8 also added the targets TYPE_USETYPE_PARAMETERList<@NonNull String>
The built-in annotations
The program uses each compiler-checked annotation in the place it belongs and then asks reflection what survived into the running program.
import java.util.ArrayList;
import java.util.List;
public class BuiltIns {
static class Base {
String label() {
return "base";
}
/** @deprecated use {@link #label()} instead. */
@Deprecated(since = "2.0", forRemoval = true)
String oldLabel() {
return label();
}
}
static class Child extends Base {
@Override // compiler checks a parent method exists
String label() {
return "child";
}
}
@FunctionalInterface // compiler checks exactly one abstract method
interface Converter {
int convert(String s);
}
@SafeVarargs // promises not to misuse the generic array
static <T> List<T> listOf(T... items) {
List<T> list = new ArrayList<>();
for (T item : items) {
list.add(item);
}
return list;
}
@SuppressWarnings("removal") // silences the deprecation warning here only
static String callOld(Base b) {
return b.oldLabel();
}
public static void main(String[] args) throws Exception {
System.out.println(new Child().label() + ", " + callOld(new Child()));
Converter c = Integer::parseInt;
System.out.println(c.convert("42") + 1);
System.out.println(listOf("a", "b"));
Deprecated d = Base.class.getDeclaredMethod("oldLabel").getAnnotation(Deprecated.class);
System.out.println("@Deprecated since " + d.since() + ", forRemoval " + d.forRemoval());
System.out.println("@Override kept at run time: "
+ (Child.class.getDeclaredMethod("label").getAnnotations().length > 0));
}
}
Output:
child, child
43
[a, b]
@Deprecated since 2.0, forRemoval true
@Override kept at run time: false
on@Override turns a mistake such as declaringChild.label() instead oflabel(int) into a compile error instead of a silent new overload. Reflection could not see it afterwards ("kept at run time: false"), because it haslabel() retention.SOURCE was visible at run time, with both elements.@Deprecated(since = "2.0", forRemoval = true) makes the compiler issue the stronger "removal" warning, whichforRemoval = true silenced for one method only.@SuppressWarnings("removal") and@FunctionalInterface are promises the compiler checks or relies on; neither changes what the code does at run time.@SafeVarargs
Defining and reading your own annotations
Two runtime annotations drive a tiny object mapper and a command dispatcher, the two most common framework uses. A third annotation has CLASS
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class CustomAnnotations {
@Retention(RetentionPolicy.RUNTIME) // keep it in the class file AND at run time
@Target(ElementType.FIELD)
@interface Column {
String name(); // required element
int length() default 255; // optional element with a default
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface Command {
String value(); // 'value' can be set without naming it
}
@Retention(RetentionPolicy.CLASS) // in the class file, invisible to reflection
@Target(ElementType.METHOD)
@interface BuildOnly {
}
static class User {
@Column(name = "user_name", length = 40)
String name;
@Column(name = "email")
String email;
String notMapped;
@Command("greet")
@BuildOnly
void greet() {
System.out.println(" hello!");
}
}
public static void main(String[] args) throws Exception {
// A tiny "ORM": generate column definitions from annotations
for (Field f : User.class.getDeclaredFields()) {
Column c = f.getAnnotation(Column.class);
if (c != null) {
String ddl = c.name() + " VARCHAR(" + c.length() + ")";
System.out.println(f.getName() + " -> " + ddl);
} else {
System.out.println(f.getName() + " -> (no @Column, skipped)");
}
}
// A tiny command dispatcher
Method m = User.class.getDeclaredMethod("greet");
Command cmd = m.getAnnotation(Command.class);
System.out.println("command name: " + cmd.value());
m.invoke(new User());
boolean visible = m.isAnnotationPresent(BuildOnly.class);
System.out.println("@BuildOnly visible at run time: " + visible);
}
}
Output:
name -> user_name VARCHAR(40)
email -> email VARCHAR(255)
notMapped -> (no @Column, skipped)
command name: greet
hello!
@BuildOnly visible at run time: false
- The mapper found
on two fields and generated column definitions.@Column did not setemail , so the default 255 applied. The field without the annotation was skipped, which is how JPA'slength -style choices are made.@Transient - An element named
can be set without its name, which is whyvalue works. The dispatcher looked the command name up and invoked the method by reflection; see@Command("greet")reflection . has@BuildOnly retention, soCLASS returned false even though it is in the class file. ForgettingisAnnotationPresent is the most common reason "my annotation is not found".@Retention(RUNTIME) limits where an annotation may appear. Putting@Target on a method would be a compile error. Without@Column , an annotation may be used on almost any declaration, which makes misuse harder to spot.@Target- Element values must be compile-time constants: literals, constant expressions, class literals or enum constants. A value computed at run time, such as a configuration property, cannot go into an annotation, which is why frameworks accept placeholders like
in strings and resolve them later."${db.url}"
Annotation objects, defaults and @Inherited
An @Audit
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Proxy;
public class AnnotationInternals {
enum Level { LOW, HIGH }
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@Inherited // subclasses "inherit" it (classes only)
@interface Audit {
String owner();
Level level() default Level.LOW; // allowed element types: primitives,
String[] tags() default {}; // String, Class, enums, annotations
Class<?> handler() default Object.class; // and one-dimensional arrays of them
}
@Audit(owner = "billing", tags = {"pci", "eu"})
static class Payments {
@Audit(owner = "ops", level = Level.HIGH)
void refund() {
}
}
static class CardPayments extends Payments {
@Override
void refund() {
}
}
@Audit(owner = "billing", tags = {"pci", "eu"})
static class Invoices {
}
public static void main(String[] args) throws Exception {
Audit a = Payments.class.getAnnotation(Audit.class);
System.out.println("toString: " + a);
System.out.println("level (default used): " + a.level() + ", handler " + a.handler()
.getSimpleName());
System.out.println("instance is a dynamic proxy: " + Proxy.isProxyClass(a.getClass()));
System.out.println("annotationType(): " + a.annotationType().getSimpleName());
// equals compares element values, so the same annotation on two classes is equal
Audit b = Invoices.class.getAnnotation(Audit.class);
System.out.println("equal across classes: " + a.equals(b) + ", same object: " + (a == b));
// @Inherited applies to class annotations only, not to overridden methods
System.out.println("CardPayments class has @Audit: "
+ CardPayments.class.isAnnotationPresent(Audit.class)
+ " (declared directly: "
+ (CardPayments.class.getDeclaredAnnotation(Audit.class) != null) + ")");
System.out.println("CardPayments.refund() has @Audit: "
+ CardPayments.class.getDeclaredMethod("refund").isAnnotationPresent(Audit.class));
}
}
Output:
toString: @AnnotationInternals.Audit(handler=java.lang.Object.class, level=LOW, tags={"pci", "eu"}, owner="billing")
level (default used): LOW, handler Object
instance is a dynamic proxy: true
annotationType(): Audit
equal across classes: true, same object: false
CardPayments class has @Audit: true (declared directly: false)
CardPayments.refund() has @Audit: false
lists every element, including the defaultstoString andhandler that the source never set. The object is a dynamic proxy, andlevel , notannotationType() , tells you which annotation it is.getClass()- The annotations on
andPayments wereInvoices , because equality is defined by the annotation type and all element values, but they were different objects. Eachequals result is a separate proxy, so compare withgetAnnotation .equals made@Inherited true, althoughCardPayments.class.isAnnotationPresent(Audit.class) found nothing on the subclass itself. It works only for class annotations inherited from a superclass. The overriding methodgetDeclaredAnnotation did not inherit its parent'srefund() , and annotations on interfaces are never inherited. Frameworks such as Spring add their own search logic for these cases.@Audit
An annotation-driven validator, and the cost of lookups
Bean Validation (@NotBlank@Min
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class Validator {
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface NotBlank {
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface Range {
int min();
int max();
}
static class Signup {
@NotBlank
String user;
@Range(min = 13, max = 120)
int age;
Signup(String user, int age) {
this.user = user;
this.age = age;
}
}
// Reads the annotations of each field and checks the value against them
static List<String> validate(Object o) throws IllegalAccessException {
List<String> problems = new ArrayList<>();
for (Field f : fields(o.getClass())) {
f.setAccessible(true);
Object v = f.get(o);
if (f.isAnnotationPresent(NotBlank.class)
&& (v == null || v.toString().isBlank())) {
problems.add(f.getName() + " must not be blank");
}
Range r = f.getAnnotation(Range.class);
if (r != null && ((int) v < r.min() || (int) v > r.max())) {
problems.add(f.getName() + " must be " + r.min() + ".." + r.max() + ", was " + v);
}
}
return problems;
}
// Reflection is slow-ish, so frameworks cache what they find per class
static final Map<Class<?>, Field[]> CACHE = new ConcurrentHashMap<>();
static Field[] fields(Class<?> c) {
return CACHE.computeIfAbsent(c, Class::getDeclaredFields);
}
public static void main(String[] args) throws Exception {
System.out.println("valid: " + validate(new Signup("ann", 30)));
System.out.println("invalid: " + validate(new Signup(" ", 7)));
// Rough cost of looking an annotation up, best of 3
Field age = Signup.class.getDeclaredField("age");
Range cached = age.getAnnotation(Range.class);
int n = 5000000;
long lookup = Long.MAX_VALUE;
long reuse = Long.MAX_VALUE;
long sink = 0;
for (int run = 0; run < 3; run++) {
long t0 = System.nanoTime();
for (int i = 0; i < n; i++) {
sink += age.getAnnotation(Range.class).max();
}
lookup = Math.min(lookup, System.nanoTime() - t0);
t0 = System.nanoTime();
for (int i = 0; i < n; i++) {
sink += cached.max();
}
reuse = Math.min(reuse, System.nanoTime() - t0);
}
System.out.printf("getAnnotation each time: %5.1f ns, cached instance: %5.1f ns%s%n",
(double) lookup / n, (double) reuse / n, sink == 0 ? "!" : "");
}
}
Output (2-CPU Linux machine, JDK 21, rough timing):
valid: []
invalid: [user must not be blank, age must be 13..120, was 7]
getAnnotation each time: 9.3 ns, cached instance: 5.1 ns
- The valid sign-up had no problems. The invalid one broke both rules, and the messages were built from the annotation's own elements, "13..120", so the rule and its message cannot drift apart.
on agetAnnotation took a few nanoseconds per call here. The JDK caches the parsed annotations per field, so later lookups are map reads; the first lookup on each element parses the class file data and is far slower.Field- The validator caches
per class, because that call copies the array on every invocation. Real frameworks build a per-class description once and reuse it, which is why the first request to a new endpoint is often noticeably slower than the rest.getDeclaredFields()
Repeatable annotations
Before Java 8, an annotation could appear at most once on an element. @Repeatable
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Arrays;
public class RepeatableDemo {
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(Schedules.class)
@interface Schedule {
String cron();
}
@Retention(RetentionPolicy.RUNTIME)
@interface Schedules { // the container the compiler uses
Schedule[] value();
}
@Schedule(cron = "0 9 * * MON")
@Schedule(cron = "0 9 * * THU")
static class Report {
}
public static void main(String[] args) {
Schedule[] all = Report.class.getAnnotationsByType(Schedule.class);
System.out.println("schedules: " + Arrays.stream(all).map(Schedule::cron).toList());
Schedule single = Report.class.getAnnotation(Schedule.class);
System.out.println("getAnnotation(Schedule): " + single);
System.out.println("stored as container: "
+ (Report.class.getAnnotation(Schedules.class) != null));
}
}
Output:
schedules: [0 9 * * MON, 0 9 * * THU]
getAnnotation(Schedule): null
stored as container: true
returned both schedules: it looks through the container automatically.getAnnotationsByType(Schedule.class) returned null, because the class file holds a singlegetAnnotation(Schedule.class) container, not two@Schedules annotations. Code written before Java 8 that uses@Schedule misses repeated annotations entirely.getAnnotation- The container must have a
element that is an array of the repeatable type, and its retention and target must be at least as wide as the repeatable annotation's.value()
Processing annotations at compile time
An annotation processor (Java 6, JSR 269) runs inside javacSOURCEMETA-INF/services/javax.annotation.processing.Processor
import java.net.URI;
import java.util.List;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic;
import javax.tools.JavaCompiler;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
public class ProcessorDemo {
// Source code to compile: a SOURCE-retention annotation and a class that uses it
static final String SOURCE = """
import java.lang.annotation.*;
@Retention(RetentionPolicy.SOURCE)
@interface Reminder { String value(); }
public class Shop {
@Reminder("add tax") double total;
@Reminder("validate input") void checkout() { }
void ship() { }
}
""";
// An annotation processor runs inside javac and sees annotations of every retention
@SupportedAnnotationTypes("Reminder")
static class ReminderProcessor extends AbstractProcessor {
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment env) {
for (TypeElement reminder : annotations) {
for (Element e : env.getElementsAnnotatedWith(reminder)) {
String note = e.getAnnotationMirrors().get(0).getElementValues().values()
.iterator().next().getValue().toString();
processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE,
"reminder on " + e.getKind() + " " + e.getSimpleName() + ": " + note);
}
}
return true;
}
}
public static void main(String[] args) {
JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
SimpleJavaFileObject file = new SimpleJavaFileObject(
URI.create("string:///Shop.java"), SimpleJavaFileObject.Kind.SOURCE) {
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return SOURCE;
}
};
JavaCompiler.CompilationTask task = javac.getTask(null, null,
d -> System.out.println("javac " + d.getKind() + ": " + d.getMessage(null)),
List.of("-proc:only"), null, List.of(file));
task.setProcessors(List.of(new ReminderProcessor()));
System.out.println("compiled: " + task.call());
}
}
Output:
javac NOTE: reminder on FIELD total: add tax
javac NOTE: reminder on METHOD checkout: validate input
compiled: true
- The processor found both uses of the
-retentionSOURCE , on a field and on a method, read their values, and reported them as compiler notes. The unannotated method@Reminder was not reported. At run time these annotations no longer exist.ship() - Processors work on the
view of the code:javax.lang.model s for declarations andElement s for annotations, because the classes being compiled cannot be loaded yet. Reporting withAnnotationMirror instead ofDiagnostic.Kind.ERROR would fail the build.NOTE runs processors without generating class files. Since JDK 23,-proc:only no longer runs processors found on the class path unless processing is requested explicitly, for example withjavac or a-proc:full ; projects that relied on implicit processing must now say so.-processorpath
Choosing a retention and a reader
| Goal | Use |
|---|---|
| A check the compiler or a processor performs | @Retention(SOURCE) |
| Information for bytecode tools only | @Retention(CLASS) |
| Configuration a framework reads at run time | @Retention(RUNTIME) |
| Generating code from annotations | An annotation processor writing new sources through Filer |
| Several values of the same kind | @RepeatablegetAnnotationsByType |
| Annotation visible on subclasses | @Inherited |
| Nullness or other type checks | TYPE_USE |
See