Lesson · Annotations & Annotation Processing
Meta-Annotations
11 min readMeta-Annotations
@Retention, @Target, @Inherited, @Documented and @Repeatable are annotations written on annotations. They decide how far an annotation travels, where it is legal to write it, who can read it back, and whether two uses are even allowed. Get the two defaults wrong and your annotation compiles, runs, and is invisible.
The annotations that govern annotations
A meta-annotation is an annotation applied to an annotation type declaration. It does not describe the code your annotation will decorate; it describes the annotation itself: how long it survives compilation, where it may be written, whether subclasses report it as theirs, whether it appears in generated documentation, and whether it can appear twice on one element.
You have already used meta-annotations without calling them that. Every annotation type in the JDK that behaves differently from the default carries them, and every custom annotation you write is shaped by the ones you add and by the ones you leave out.
Retention decides who can ever see the annotation; target decides where it is legal to say it.
Retention: how far an annotation travels
Every annotation has a retention policy, and the default is the one that surprises people: CLASS, not RUNTIME. The policy is a promise about how far the annotation travels, and it is set on the declaration, never at the use site.
| Retention | In the source | In the class file | Visible to reflection | Choose it when |
|---|---|---|---|---|
| SOURCE | yes | no | no | the reader is javac or an annotation processor: @Override, @SuppressWarnings, @Serial |
| CLASS | yes | yes | no | a bytecode tool is the reader; also the default when the declaration says nothing |
| RUNTIME | yes | yes | yes | a framework or library scans it while your program runs: @Test, @Component, @Column |
- Only RUNTIME reaches reflection: getAnnotation and friends return null for SOURCE and CLASS annotations, with no error and no warning.
- CLASS is what you get by omission: the compiler records it in the class file as RuntimeInvisibleAnnotations, an attribute the VM does not read at run time.
- SOURCE is a complete answer for a processor: processors read the source model, so an annotation that only ever feeds compile-time checks does not need to travel at all.
- The policy lives on the annotation declaration: @Retention cannot be varied per use site, and a separate annotation type with a different policy is the only way to change it.
Writing an annotation meant for reflection and forgetting @Retention(RUNTIME) is the most common annotation bug in the language: nothing errors, the reader just finds null.
Retention · how far an annotation travels
the policy is set on the declaration
Everything is visible while the compiler reads it. Element types, targets and values are all checked here.
What survives compilation sits in attributes on the declaration. Tools that read .class bytes can still see it.
Only here does getAnnotation work, and only for annotations the VM was asked to retain.
who stands where
@Target: where it is legal to write it
If @Target is absent, the annotation may be written as a modifier for any declaration. Once present, javac enforces the list, and a use in the wrong context is a compile error rather than a warning. The constants arrived with the language over three JDKs.
| ElementType | Legal on | Since |
|---|---|---|
| TYPE | a class, interface, enum, annotation type or record declaration | Java 5 |
| FIELD | a field declaration, enum constants included | Java 5 |
| METHOD | a method declaration | Java 5 |
| PARAMETER | a formal parameter declaration | Java 5 |
| CONSTRUCTOR | a constructor declaration | Java 5 |
| LOCAL_VARIABLE | a local variable declaration | Java 5 |
| ANNOTATION_TYPE | an annotation type declaration, what a meta-annotation needs | Java 5 |
| PACKAGE | a package declaration in package-info.java | Java 5 |
| TYPE_PARAMETER | a type parameter declaration such as <@Immutable T> | Java 8 |
| TYPE_USE | any type context: generics, arrays, casts, throws, extends and implements, plus class declarations and type parameter declarations | Java 8 |
| MODULE | a module declaration in module-info.java | Java 9 |
| RECORD_COMPONENT | a component in a record header | JDK 16 |
- Declaration contexts are the original eleven: the annotation sits before a declaration of the kind named. The other two are different in nature: TYPE_USE follows the type wherever the type is written.
- TYPE_USE is one target for every type position: that is why nullness and immutability annotations use it, so a static analyser sees List<@NonNull String> and not just the variable declaration.
- TYPE_PARAMETER is the declaration form: <@Immutable T> annotates the type parameter itself rather than a use of it.
- @Target({}) is legal and means nowhere: the annotation can be written on nothing directly, which is the trick behind member interfaces inside complex annotation types.
If a use site fails with annotation type not applicable, the fix belongs in the @Target line on the declaration, not at the call site.
Meta-annotation lab · retention meets target
pick one of eachretention
the default when you say nothing
target
@Retention(CLASS) @Target(METHOD)
in the file, invisible to the JVMthe class file keeps it as RuntimeInvisibleAnnotations, so bytecode tools see it; the VM does not read it for reflection.
who can see it
where it is legal
a method declaration
a realistic use: @Retry on fetch(), read by a retry wrapper when the call fails
a concern about one parameter needs PARAMETER on the parameter itself; the method target does not cover nested declarations.
The combination compiles and bytecode tools see it, but a reflective reader finds nothing. Say CLASS out loud when you mean it, instead of inheriting it by silence.
Repeating, inheriting, documenting
Three more meta-annotations change how an annotation behaves once it has been written:
- @Repeatable (Java 8) names a container. You declare @Schedule plus a container @Schedules whose single element is Schedule[], and two @Schedule lines on one method are wrapped into one @Schedules by the compiler. Reading them back takes getAnnotationsByType(Schedule.class); getAnnotation(Schedule.class) does not look through the container and returns null once wrapping has happened.
- @Inherited walks the superclass chain only. An annotation on a superclass is found by getAnnotations (and by getAnnotation) on the subclass, unless the subclass declares the annotation itself. Annotations on implemented interfaces are never inherited, and the annotation type needs @Inherited for any of it to happen.
- @Documented puts the annotation in generated documentation. Without it, Javadoc leaves the annotation out of the page, which is why the JDK's own @Deprecated and @SafeVarargs carry it.
- The container has a fixed shape: exactly one element named value whose type is an array of the repeatable annotation, and a retention and target at least as broad as the annotation it wraps.
Write the annotation twice; the compiler writes the container. Repetition is a source-level convenience, not a runtime concept.
Defaults, and the bug they cause
Every meta-annotation you do not write takes its default, and the defaults were chosen for the compiler rather than for you: no @Retention means CLASS, no @Target means any declaration. Here is the failure that follows, walked through in the order it usually happens.
- Declare @interface ApiNote with @Target(METHOD) and nothing else. Retention silently defaults to CLASS.
- Write it on a method. The build stays green, and a test that inspects the class file or the source model finds the annotation exactly where it should be, which feels like proof that everything works.
- Ship the jar. A runtime library calls method.getAnnotation(ApiNote.class) and gets null, because CLASS retention never reaches reflection. There is no error, and the caller treats the missing annotation as the default configuration.
- Fix it by adding @Retention(RUNTIME) to the annotation declaration. No use site changes; the same jar now answers the lookup.
- When the reader is javac or a processor, the opposite choice is correct: SOURCE is enough, and it documents that nothing downstream needs the annotation.
- Decide the reader first, then write the retention line as part of declaring the annotation, in the same sitting, so it cannot be forgotten.
Match the retention to the consumer: SOURCE for the compiler and processors, RUNTIME for reflection, and CLASS only when a bytecode tool reads the class file.
Green tests, an invisible annotation in the jar
An annotation declared without @Retention defaults to CLASS: it is compiled into the class file and is invisible to anything that asks at run time. The test that passed was inspecting the class file or the source model, so it proved the annotation survives the compiler, not that it reaches a reflective reader. The runtime library then asked for it, received null, and quietly took its default path. The same jar can even hold two annotations that disagree, one RUNTIME and one silently CLASS, which is why the retention line belongs in the same commit as the annotation declaration.
Interview angles
What is the default retention, and why does it surprise people?+
CLASS: recorded in the class file, invisible to reflection. People expect RUNTIME because their annotations are read while the program runs, but the default is the one that costs nothing at run time unless you ask for it.
That default is also why the JDK's own reflection-facing annotations, such as @Deprecated or @FunctionalInterface, state @Retention(RUNTIME) explicitly. Omission is never an opinion about run time; it is the compiler's default.
getAnnotation returns null although the annotation is on the method. What do you check first?+
The retention on the annotation declaration: SOURCE is discarded by the compiler and CLASS is invisible at run time, so only @Retention(RUNTIME) can be read back. Then check that you are querying the same element and the right class loader.
Reflection also distinguishes getAnnotation from getDeclaredAnnotation: the first consults @Inherited superclass lookups, the second sees only what is directly present.
Does @Inherited work through interfaces?+
No. It walks the superclass chain of a class and nothing else: annotations on implemented interfaces are not inherited, and the annotation type must carry @Inherited for the lookup to travel at all.
Follow-up: How do repeatable annotations travel? getAnnotationsByType consults the superclass only when the class has none of its own, directly or through a container.
Why not put @Retention(RUNTIME) on everything?+
Because retention is a contract: RUNTIME says every reflective reader may act on this annotation and it must be kept by the VM. When the reader is javac or a processor, SOURCE states that plainly and documents why nothing at run time should depend on it.
Common misconception: That SOURCE annotations are weaker or less official. The compiler gives a SOURCE annotation exactly the same checks, such as the error that @Override produces; it simply does not ship it.