Lesson · Annotations & Annotation Processing
Consuming Annotations
12 min readConsuming Annotations
An annotation has no behaviour, so every lesson about annotations is really about the consumer that believes it. This one covers both consumers: reading annotations at run time through reflection, and reading them at compile time inside an annotation processor that can fail the build or generate code.
Runtime reading: reflection asks the questions
Reflection basics already covered Class, Method and Field and how invoke works; this lesson assumes that API and starts at the annotation layer on top of it. When an annotation has RUNTIME retention, it is part of the class file, and every AnnotatedElement exposes it: isAnnotationPresent to test, getAnnotation to fetch an instance, getAnnotations to enumerate, getAnnotationsByType when repeats are involved.
The instance you get back is a proxy the JDK creates, not an object your code wrote. Calling its element methods is how values are read, and the values include every default you never wrote at the use site. Nothing about the proxy is shared state: array-valued elements come back as a fresh clone on each call, and equality is defined by the annotation contract, so two instances are equal when every element is equal, with arrays compared element by element.
- Two lookups, two meanings: getAnnotation reports annotations that are present, which includes @Inherited superclass lookups; getDeclaredAnnotation only reports what is directly on the element.
- Repeatable reads go through the container: getAnnotationsByType(Retry.class) looks inside the compiler-generated wrapper. getAnnotation(Retry.class) does not, so it returns null as soon as two uses were wrapped.
- Proxies, not your class: getClass() on an annotation returns an implementation class, while annotationType() returns the real annotation interface. Use it when you need the type rather than an instance.
- Every lookup walks metadata, so frameworks cache: they scan the class path once at startup and keep the answer, which is the pattern the frameworks lesson takes apart in detail. Your own code should do the same if it reads annotations in a hot path.
Reflection does not run the annotation; it returns a proxy whose methods read stored values. Nothing happens until your code calls them.
Compile-time reading: an annotation processor
The other consumer lives inside javac. An annotation processor is a class javac instantiates and calls once per round with the elements that carry the annotations it supports. It can fail the build with a diagnostic tied to a declaration, or write new source files that are compiled in the next round, which is how generated mappers, builders and boilerplate arrive in the same build.
- Discovery: javac looks on the processor path (--processor-path, or the class path when no path is given) for entries in META-INF/services/javax.annotation.processing.Processor, unless the build names processors explicitly with -processor.
- One instance per run: javac calls the no-arg constructor once, then init(ProcessingEnvironment) once. getSupportedAnnotationTypes and getSupportedSourceVersion are read once, not per round.
- Rounds: process is called with the annotation types present on the elements of the current round. Returning true claims those annotations, and later processors are not asked about them; returning false leaves them unclaimed.
- Tools: the Filer creates source files, class files or resources, the Messager reports notes, warnings and errors tied to an element, and Elements and Types turn names and types from the model into usable handles.
- The last round has no new inputs and processingOver() reports true. Files generated after that are not processed, so anything that must be checked belongs in an earlier round.
- Afterwards javac compiles the original and the generated sources together, so the output is ordinary code that needs no scanning at run time.
- Processors read the source model, not reflection: Element, TypeElement and ExecutableElement describe declarations, and a type mirror is the model's read-only view of a type, not a runtime Class.
- The usual output is generated code: an interface in, an implementation out, in the shape of a mapper or a builder; or a service file written from an annotated interface.
- Generated sources need a home the build compiles: they must land in a directory the compiler also reads and the IDE can see, or the project spends its time half compiled.
- Since JDK 25 processing runs only when the build asks for it: an explicit -processor, a processor path, or -proc:full. Earlier releases ran it by default whenever a processor was found on the class path.
- Processors can stop a build: a Messager error fails compilation with a message attached to the offending element, which is how validation that needs type information stays a build failure rather than a runtime surprise.
- Compiler-internal tricks are out of scope: tools such as Lombok reach into javac internals rather than using this API, and they break when those internals move.
An annotation processor moves work from run time to build time: the build pays, and the result is plain code with nothing to scan.
Consumers · one annotation, three pipelines
the reader decides which retention is enough
Runtime reflection
the reader runs inside the JVM
needs RUNTIME: SOURCE and CLASS are invisible here
Annotation processor
the reader runs inside javac
SOURCE is enough: the source model is the input
Bytecode post-processing
the reader runs inside the build
needs CLASS or RUNTIME: the bytes must carry it
Three strategies, one table
Everything frameworks do with annotations is one of three strategies, and the choice is about where you want to pay and what you want to debug.
| Strategy | When it reads | Startup cost | Native image | What you debug |
|---|---|---|---|---|
| Runtime reflection | on the first call, or in a startup scan | a lookup per call unless the result is cached | needs reachability metadata for the members read | behaviour with no source line of your own |
| Annotation processor | during compilation, in rounds | none: the wiring is already code | plain code, nothing to register | generated sources you can read and step through |
| Bytecode post-processing | at build time, after javac | none: calls are rewritten in the class file | plain bytecode, as long as the rewrite runs first | class files changed by a tool, invisible in source |
- Reflection is for wiring that is data: plugins, configuration, test runners, anything registered dynamically and read a bounded number of times.
- A processor is for wiring that is repetitive: mappers, builders, serializers, boilerplate that must be typed and checked by the compiler.
- Bytecode tools are for changes that are cross-cutting: instrumentation, weaving and call rewriting that no source construct can express; AspectJ-style weaving is the honest example.
- Debugging favours generated code: a stack trace into a generated mapper names a real line, while a reflective failure usually names only the framework that performed the lookup.
Compare strategies in the consumer's world: what happens at startup, what an ahead-of-time build can see, and what a stack trace can show.
Consumer lab · requirement meets strategy
authored verdicts, no benchmarksthe requirement
the program is compiled ahead of time, so nothing may depend on a class path scan
the strategy
getAnnotation at the call site or in a startup scan
verdict
works only if the build ships reflection metadata
Native images keep reflection, but only for members the build knows about: every reflectively accessed member needs reachability metadata, which the tracing agent can collect for you. Miss one and the lookup fails at run time instead of quietly returning null, and no JVM test ever saw it coming.
where the annotation is read
the annotation travels with the class file and is read when the program asks
Retention must match the consumer
The reader decides the retention, and both mismatches are silent. A processor reads the source, so SOURCE is enough for it, and that same annotation does not exist for any runtime lookup. A RUNTIME annotation on a class that the processor never sees, such as a compiled dependency, is never processed either, because processing walks the round's sources and not the class path.
- SOURCE for the compiler and processors: @Override, @SuppressWarnings and @Serial stop there on purpose, and nothing downstream should depend on them.
- CLASS for bytecode tools: the class file keeps it and reflection does not, so choose it deliberately rather than by omission.
- RUNTIME for reflection: the only policy that getAnnotation can read, and the one every framework that scans at startup requires.
- One annotation can serve both: RUNTIME is still fully visible in the source model, so a processor keeps working while reflection gains access. The reverse fails: SOURCE never becomes readable at run time, however convenient that would be.
Ask what will read the annotation before writing it. Retention is a consequence of that answer, and a mismatch never raises an error.
The retention that matched the wrong consumer
Two versions of one mistake. A processor validates @Route and generates a dispatcher from it, so @Route is declared with SOURCE retention on purpose. Months later a health endpoint wants to list the routes and reads them with reflection: the list comes back empty, the endpoint reports zero routes, and nothing errors because absence is a legal answer. The mirror image: @Route is RUNTIME so a test could assert on it reflectively, and the team assumes the processor validates it too, but the processor only runs over the sources being compiled, so routes living on a dependency jar were never in a round. Decide the consumer first, write the retention to match it, and make the consumer prove itself: a startup check that the scan found at least one annotation turns a silent mismatch into a loud failure.
Interview angles
getAnnotation returns null although the annotation is visibly on the method. Why?+
Retention, almost always: SOURCE is discarded by the compiler and CLASS is invisible at run time, so only @Retention(RUNTIME) can be read. After that, check that you are asking the same element and the class loader that defined it.
Common misconception: That having the annotation class on the class path is enough for reflection. The class file has to carry the annotation in the first place, and that is the retention decision.
When do you need getAnnotationsByType instead of getAnnotation?+
When the annotation is repeatable. getAnnotationsByType looks through the container the compiler generated, while getAnnotation only reports directly present annotations (plus @Inherited superclass lookups), so it returns null once two uses were wrapped.
It is also the safer read for a single use, since it returns an array of length one rather than an instance that may or may not have been wrapped.
What does an annotation processor give you that reflection cannot?+
A verdict while the code is being compiled plus code you do not have to write: it can fail the build with a message tied to a declaration, and it can generate ordinary source that is compiled in the same run, so nothing is scanned or interpreted later.
That makes it the strategy that survives ahead-of-time compilation and native images unchanged: there is no reflective lookup to configure, only generated code and direct calls.
How does javac find a processor, and how do you see what it did?+
The build either names it with -processor or places it on the processor path, where javac finds it through META-INF/services/javax.annotation.processing.Processor. Since JDK 25, processing itself runs only when the build asks for it.
Common misconception: That writing the processor class is enough. Without the service entry or an explicit name, javac never instantiates it at all.
Follow-up: To watch it work, add -XprintRounds and -XprintProcessorInfo, which show each round and which annotations each processor was asked to handle.