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

An annotation (Java 5, JSR 175) is a marker such as @Override or @Column(name = "email") placed on a declaration. It does nothing by itself; some program has to look for it. Who can see it is decided by its retention policy, set with the meta-annotation @Retention:

  • SOURCE: discarded by the compiler. Only the compiler itself and annotation processors see it. @Override and @SuppressWarnings work this way.
  • CLASS, the default: written into the class file but not loaded at run time. Bytecode tools can read it; reflection cannot.
  • RUNTIME: written into the class file in the RuntimeVisibleAnnotations attribute and available through reflection. Frameworks such as JPA, Spring and JUnit rely on this.

An annotation type is declared with @interface. Its methods are its elements, which may have defaults and are limited to primitives, String, Class, enums, other annotations, and one-dimensional arrays of these. At run time, reflection returns an object implementing the annotation interface; in the JDK it is a dynamic proxy whose handler holds the element values read from the class file.

Built-in and meta-annotations
AnnotationSinceRead byPurpose
@OverrideJava 5CompilerFail if the method does not override or implement anything
@DeprecatedJava 5; since and forRemoval in Java 9Compiler, tools, reflectionWarn users of an API that is going away
@SuppressWarningsJava 5CompilerSilence named warnings in one declaration
@SafeVarargsJava 7CompilerPromise that a generic varargs method is safe
@FunctionalInterfaceJava 8CompilerFail unless the interface has exactly one abstract method
@Retention, @Target, @Documented, @InheritedJava 5Compiler, reflectionMeta-annotations that configure annotation types
@RepeatableJava 8CompilerAllow the same annotation more than once on an element

Java 8 also added the targets TYPE_USE and TYPE_PARAMETER, so annotations can be placed on any use of a type, such as List<@NonNull String>, which checkers like the Checker Framework read. The examples here ran on JDK 21.

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.

Java
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:

Output
child, child
43
[a, b]
@Deprecated since 2.0, forRemoval true
@Override kept at run time: false
  • @Override on Child.label() turns a mistake such as declaring label(int) instead of label() into a compile error instead of a silent new overload. Reflection could not see it afterwards ("kept at run time: false"), because it has SOURCE retention.
  • @Deprecated(since = "2.0", forRemoval = true) was visible at run time, with both elements. forRemoval = true makes the compiler issue the stronger "removal" warning, which @SuppressWarnings("removal") silenced for one method only.
  • @FunctionalInterface and @SafeVarargs are promises the compiler checks or relies on; neither changes what the code does at run time.

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 retention, to show what reflection cannot see.

Java
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:

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 @Column on two fields and generated column definitions. email did not set length, so the default 255 applied. The field without the annotation was skipped, which is how JPA's @Transient-style choices are made.
  • An element named value can be set without its name, which is why @Command("greet") works. The dispatcher looked the command name up and invoked the method by reflection; see reflection.
  • @BuildOnly has CLASS retention, so isAnnotationPresent returned false even though it is in the class file. Forgetting @Retention(RUNTIME) is the most common reason "my annotation is not found".
  • @Target limits where an annotation may appear. Putting @Column on a method would be a compile error. Without @Target, an annotation may be used on almost any declaration, which makes misuse harder to spot.
  • 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 "${db.url}" in strings and resolve them later.

Annotation objects, defaults and @Inherited

An @Audit annotation with several element types is placed on two unrelated classes with identical values, and on a class and method that a subclass then extends and overrides.

Java
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:

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
  • toString lists every element, including the defaults handler and level that the source never set. The object is a dynamic proxy, and annotationType(), not getClass(), tells you which annotation it is.
  • The annotations on Payments and Invoices were equals, because equality is defined by the annotation type and all element values, but they were different objects. Each getAnnotation result is a separate proxy, so compare with equals.
  • @Inherited made CardPayments.class.isAnnotationPresent(Audit.class) true, although getDeclaredAnnotation found nothing on the subclass itself. It works only for class annotations inherited from a superclass. The overriding method refund() did not inherit its parent's @Audit, and annotations on interfaces are never inherited. Frameworks such as Spring add their own search logic for these cases.

An annotation-driven validator, and the cost of lookups

Bean Validation (@NotBlank, @Min) works by reading field annotations and checking values against them. The validator below does the same with two annotations, on one valid and one invalid sign-up, and then measures what an annotation lookup costs. Best of 3 runs, a rough comparison.

Java
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):

Output
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.
  • getAnnotation on a Field 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.
  • The validator caches getDeclaredFields() 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.

Repeatable annotations

Before Java 8, an annotation could appear at most once on an element. @Repeatable allows more, by naming a container annotation that the compiler wraps the repeats in. A report scheduled twice a week shows both views of the result.

Java
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:

Output
schedules: [0 9 * * MON, 0 9 * * THU]
getAnnotation(Schedule): null
stored as container: true
  • getAnnotationsByType(Schedule.class) returned both schedules: it looks through the container automatically.
  • getAnnotation(Schedule.class) returned null, because the class file holds a single @Schedules container, not two @Schedule annotations. Code written before Java 8 that uses getAnnotation misses repeated annotations entirely.
  • The container must have a value() 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.

Processing annotations at compile time

An annotation processor (Java 6, JSR 269) runs inside javac and sees annotations of every retention, including SOURCE. Processors generate code (Lombok, MapStruct, Dagger and record builders work this way) or report errors. To keep the example self-contained, the program compiles a small source string with the compiler API and registers its processor directly; a real processor is listed in META-INF/services/javax.annotation.processing.Processor in a JAR on the compiler's processor path.

Java
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:

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 SOURCE-retention @Reminder, on a field and on a method, read their values, and reported them as compiler notes. The unannotated method ship() was not reported. At run time these annotations no longer exist.
  • Processors work on the javax.lang.model view of the code: Elements for declarations and AnnotationMirrors for annotations, because the classes being compiled cannot be loaded yet. Reporting with Diagnostic.Kind.ERROR instead of NOTE would fail the build.
  • -proc:only runs processors without generating class files. Since JDK 23, javac no longer runs processors found on the class path unless processing is requested explicitly, for example with -proc:full or a -processorpath; projects that relied on implicit processing must now say so.

Choosing a retention and a reader

Annotation design choices
GoalUse
A check the compiler or a processor performs@Retention(SOURCE) and an annotation processor
Information for bytecode tools only@Retention(CLASS), the default
Configuration a framework reads at run time@Retention(RUNTIME) and reflection, with results cached per class
Generating code from annotationsAn annotation processor writing new sources through Filer
Several values of the same kind@Repeatable, read with getAnnotationsByType
Annotation visible on subclasses@Inherited for class annotations; your own search for methods and interfaces
Nullness or other type checksTYPE_USE annotations with a checker

See reflection for reading annotations together with other class metadata, dynamic proxies for the mechanism behind annotation objects, and JUnit 5 for a framework built on annotations.