Java Annotation Processors: Generating Source Code at Compile Time
Write a Java annotation processor: AbstractProcessor, @SupportedAnnotationTypes, processing rounds, RoundEnvironment, the javax.lang.model element API, AnnotationMirror, Filer and Messager, plus how to register processors with javac, Maven and Gradle and why Lombok is different.
kvi5hnuCode Sprout team member10 min readOn this page
Reading annotations with reflection (article 108) happens while the program runs, and it costs time on every call. Annotation processors run inside the compiler instead. They inspect annotations in source code and generate new files, usually more Java source, which is then compiled with the rest of the program and runs at full speed. Dagger, MapStruct, Micronaut, AutoValue, Immutables, JMH and the JPA static metamodel all work this way. This article rebuilds the annotation-driven toString from article 108 as a compile-time code generator.
How annotation processing works
Annotation processing is built into javac. You name processors on the command line:
javac -processor ProcessorClassName1,ProcessorClassName2 sourceFiles
The compiler finds the annotations in the source files and runs each processor in turn, giving it the annotations it declared an interest in. If a processor creates a new source file, the compiler starts another round with the new files as input. When a round produces no new source files, everything (the original and generated sources) is compiled.

Writing a processor
A processor implements javax.annotation.processing.Processor, usually by extending AbstractProcessor. You declare the annotation types it supports and implement process:
@SupportedAnnotationTypes("gallery.Describe")
public class DescribeProcessor extends AbstractProcessor {
@Override public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
@Override public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment currentRound) {
...
}
}
@SupportedAnnotationTypescan list specific annotation types, wildcards such as"com.example.*"for all annotations in a package and its subpackages, or"*"for every annotation.- Override
getSupportedSourceVersionto returnlatestSupported(), or use@SupportedSourceVersion. Otherwise you get warnings on newer source levels. processis called once per round. It receives the annotation types found in this round that the processor supports, and aRoundEnvironmentdescribing the round. Returningtrueclaims those annotations, so no later processor sees them.- Through the inherited
processingEnvfield you get theFilerfor creating files, theMessagerfor reporting errors and warnings, and helper classesElementsandTypes.
The language model API
At compile time there are no Class objects yet. Processors analyze the program with the language model API in javax.lang.model, which describes code by the rules of the Java language, while reflection describes the virtual machine's view. The compiler gives you a tree of elements:
Compile time (javax.lang.model.element) | Runtime (java.lang.reflect) |
|---|---|
TypeElement (class, interface, enum, record) | Class |
VariableElement (field, parameter, local variable) | Field, Parameter |
ExecutableElement (method, constructor) | Method, Constructor |
RecordComponentElement | RecordComponent |
AnnotatedConstruct (getAnnotation, getAnnotationsByType, getAnnotationMirrors) | AnnotatedElement |
The highlights:
currentRound.getElementsAnnotatedWith(annotationTypeElement)returns all elements carrying an annotation. An overload takes a set of annotation types, which is handy for a repeatable annotation together with its container.TypeElement.getEnclosedElements()lists a class's fields, constructors and methods in source order.getSimpleName()on any element, orgetQualifiedName()on aTypeElement, returns aName. CalltoString()orcontentEquals(...)on it.getKind()tells you whether an element is aCLASS,METHOD,FIELDand so on.
Reading annotation values: getAnnotation versus AnnotationMirror
AnnotatedConstruct.getAnnotation(Describe.class) works if the annotation's class is available to the processor. That's the usual setup, where the annotation is in a separate JAR on the processor path. If it isn't, as in our demo where the annotation is compiled in the same run, read **AnnotationMirror**s instead. element.getAnnotationMirrors() lists the annotations as compile-time data, and elements.getElementValuesWithDefaults(mirror) gives each element's value. Mirrors are also the only safe way to read Class-valued elements, because calling such a method on a getAnnotation result throws MirroredTypeException.
Generating the describe code
Generated code is ordinary Java, so it can't peek at private fields the way reflection can. It has to go through getters, which is why the annotation now sits on accessor methods rather than on fields:
@Describe
public class Tile {
...
@Describe(withName = false) public Pixel getCorner() { return corner; }
@Describe public int getWidth() { return width; }
@Describe public int getHeight() { return height; }
}
From those annotations the processor writes a helper class, Descriptions. It holds one describe overload per annotated class and a catch-all describe(Object):
public static String describe(Tile obj) {
var parts = new java.util.StringJoiner(", ", "Tile{", "}");
parts.add(describe(obj.getCorner()));
parts.add("width=" + describe(obj.getWidth()));
parts.add("height=" + describe(obj.getHeight()));
return parts.toString();
}
public static String describe(Object obj) { return String.valueOf(obj); }
Article 108 walked nested objects with a recursive call at runtime. Here the compiler's ordinary overload resolution does that job: describe(obj.getCorner()) binds to the generated describe(Pixel), while describe(obj.getWidth()) has no specific overload and lands in describe(Object).
The process method creates the file through the Filer and writes one method per annotated class:
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment currentRound) {
if (annotations.isEmpty()) return true; // later rounds: don't create the file again
try {
JavaFileObject sourceFile = processingEnv.getFiler().createSourceFile("gallery.Descriptions");
try (var out = new PrintWriter(sourceFile.openWriter())) {
// print the package and class header
for (Element e : currentRound.getElementsAnnotatedWith(annotations.iterator().next()))
if (e instanceof TypeElement te) writeDescribeMethod(out, te);
// print describe(Object) and the closing brace
}
} catch (IOException ex) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Cannot write Descriptions: " + ex);
}
return true;
}
writeDescribeMethod emits the method signature and a StringJoiner whose prefix includes the class name only when the class-level @Describe has withName set. It then visits te.getEnclosedElements() in source order and, for each annotated getter, adds one parts.add(...) line, prefixed with a label such as width= (derived from getWidth) when that getter's withName is true.
The early return at the top of process matters. Once the generated file exists, javac runs further rounds with an empty annotation set, and a second createSourceFile for the same name would fail with a FilerException.
Reporting errors
A processor should report misuse as a compiler error at the right location, not throw an exception:
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
"@Describe methods must not have parameters", methodElement);
The error appears like any other compile error, with file and line, and IDEs underline the offending element. The demo's second compilation shows this.
Seeing the rounds
Run javac with -XprintRounds to watch the rounds:
Round 1:
input files: {gallery.Pixel, gallery.Tile, gallery.Demo}
annotations: [gallery.Describe]
last round: false
Round 2:
input files: {gallery.Descriptions}
annotations: []
last round: false
Round 3:
input files: {}
annotations: []
last round: true
To run a processor from the command line, compile it first, then use it while compiling your code. -s sets where generated sources go:
javac DescribeProcessor.java
javac -processor DescribeProcessor -s generated -d classes gallery/*.java
java -cp classes gallery.Demo
Packaging and using processors
In real projects, processors come as JARs:
- A processor JAR registers itself in
META-INF/services/javax.annotation.processing.Processor, or withprovides javax.annotation.processing.Processor with ...in its module descriptor, so the compiler can discover it viaServiceLoaderwhen it's on the processor path. - In Maven, add the processor JARs under
annotationProcessorPathsof themaven-compiler-plugin. In Gradle, use theannotationProcessordependency configuration. - Generated sources usually land in
target/generated-sources/annotationsorbuild/generated/sources/annotationProcessor, and IDEs pick them up. - Processors can generate any file through
Filer.createResource, such as configuration, service registrations, XML descriptors, scripts or documentation, not just Java source.
A complete example
To be self-contained, the demo is a small build tool. It writes the sources of Describe, Pixel, Tile and Demo to a temporary directory and compiles them through the javax.tools.JavaCompiler API, the same compiler as the javac command, with DescribeProcessor registered via task.setProcessors. It prints each round, shows the generated Descriptions.java, loads and runs the compiled Demo, and confirms that the SOURCE-retention annotation isn't in the class files. Finally, it compiles a bad class to show a processor-reported error. This requires a JDK, because a plain runtime doesn't include the compiler.
import java.io.*;
import java.net.*;
import java.nio.file.*;
import java.util.*;
import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.*;
import javax.tools.*;
public class Solution {
/** Generates gallery.Descriptions with one describe method per @Describe class. */
@SupportedAnnotationTypes("gallery.Describe")
public static class DescribeProcessor extends AbstractProcessor {
private int round;
@Override public SourceVersion getSupportedSourceVersion() { return SourceVersion.latestSupported(); }
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment env) {
round++;
System.out.println(" [processor] round " + round + ": annotations=" + names(annotations)
+ ", root elements=" + names(env.getRootElements()) + (env.processingOver() ? ", last round" : ""));
if (annotations.isEmpty()) return true; // later rounds: nothing to do
TypeElement describeType = annotations.iterator().next();
var classes = new ArrayList<TypeElement>();
for (Element e : env.getElementsAnnotatedWith(describeType)) {
if (e instanceof TypeElement te) classes.add(te);
else if (e instanceof ExecutableElement m && !m.getParameters().isEmpty())
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
"@Describe methods must not have parameters", m);
}
classes.sort(Comparator.comparing(te -> te.getQualifiedName().toString()));
try {
JavaFileObject file = processingEnv.getFiler().createSourceFile("gallery.Descriptions");
try (var out = new PrintWriter(file.openWriter())) {
out.println("// Generated by DescribeProcessor. Do not edit.");
out.println("package gallery;");
out.println("@javax.annotation.processing.Generated(\"DescribeProcessor\")");
out.println("public final class Descriptions {");
for (TypeElement te : classes) writeMethod(out, te, describeType);
out.println(" public static String describe(Object obj) { return String.valueOf(obj); }");
out.println("}");
}
} catch (IOException ex) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "cannot write Descriptions: " + ex);
}
return true; // we claim @Describe
}
private void writeMethod(PrintWriter out, TypeElement te, TypeElement describeType) {
String className = te.getQualifiedName().toString();
String prefix = withName(te, describeType) ? te.getSimpleName() + "{" : "{";
out.println(" public static String describe(" + className + " obj) {");
out.println(" var parts = new java.util.StringJoiner(\", \", \"" + prefix + "\", \"}\");");
for (Element member : te.getEnclosedElements()) { // source order
if (member.getKind() != ElementKind.METHOD || annotation(member, describeType) == null) continue;
String method = member.getSimpleName().toString();
String label = withName(member, describeType) ? "\"" + propertyName(method) + "=\" + " : "";
out.println(" parts.add(" + label + "describe(obj." + method + "()));");
}
out.println(" return parts.toString();");
out.println(" }");
}
// read the annotation through the language model (the annotation class isn't loadable here)
private static AnnotationMirror annotation(Element e, TypeElement type) {
for (AnnotationMirror m : e.getAnnotationMirrors())
if (m.getAnnotationType().asElement().equals(type)) return m;
return null;
}
private boolean withName(Element e, TypeElement type) {
AnnotationMirror m = annotation(e, type);
for (var entry : processingEnv.getElementUtils().getElementValuesWithDefaults(m).entrySet())
if (entry.getKey().getSimpleName().contentEquals("withName"))
return (Boolean) entry.getValue().getValue();
return true;
}
private static String propertyName(String getter) { // getWidth -> width
String s = getter.replaceFirst("^(get|is)", "");
return Character.toLowerCase(s.charAt(0)) + s.substring(1);
}
private static String names(Collection<? extends Element> elements) {
return elements.stream().map(e -> e instanceof TypeElement t ? t.getQualifiedName().toString() : e.toString())
.sorted().toList().toString();
}
}
static final Map<String, String> SOURCES = new LinkedHashMap<>();
static {
SOURCES.put("gallery/Describe.java", """
package gallery;
import java.lang.annotation.*;
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.SOURCE)
public @interface Describe { boolean withName() default true; }
""");
SOURCES.put("gallery/Pixel.java", """
package gallery;
@Describe(withName = false)
public class Pixel {
private final int x, y;
public Pixel(int x, int y) { this.x = x; this.y = y; }
@Describe(withName = false) public int getX() { return x; }
@Describe(withName = false) public int getY() { return y; }
}
""");
SOURCES.put("gallery/Tile.java", """
package gallery;
@Describe
public class Tile {
private final Pixel corner;
private final int width, height;
public Tile(Pixel corner, int width, int height) {
this.corner = corner; this.width = width; this.height = height;
}
@Describe(withName = false) public Pixel getCorner() { return corner; }
@Describe public int getWidth() { return width; }
@Describe public int getHeight() { return height; }
public int area() { return width * height; }
}
""");
SOURCES.put("gallery/Demo.java", """
package gallery;
public class Demo {
public static void main(String[] args) {
var tile = new Tile(new Pixel(3, 7), 16, 9);
System.out.println(Descriptions.describe(tile)); // Descriptions is generated!
}
}
""");
}
static boolean compile(Path root, Map<String, String> sources, StringWriter diagnostics) throws IOException {
Path src = root.resolve("src"), classes = root.resolve("classes"), gen = root.resolve("gen");
for (Path p : List.of(src, classes, gen)) Files.createDirectories(p);
var files = new ArrayList<File>();
for (var e : sources.entrySet()) {
Path f = src.resolve(e.getKey());
Files.createDirectories(f.getParent());
Files.writeString(f, e.getValue());
files.add(f.toFile());
}
JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
var collector = new DiagnosticCollector<JavaFileObject>();
try (StandardJavaFileManager fm = javac.getStandardFileManager(collector, Locale.US, null)) {
JavaCompiler.CompilationTask task = javac.getTask(null, fm, collector,
List.of("-d", classes.toString(), "-s", gen.toString()),
null, fm.getJavaFileObjectsFromFiles(files));
task.setProcessors(List.of(new DescribeProcessor())); // like javac -processor DescribeProcessor
boolean ok = task.call();
for (var d : collector.getDiagnostics())
diagnostics.write(" [javac] " + d.getKind() + ": " + d.getMessage(Locale.US) + "\n");
return ok;
}
}
public static void main(String[] args) throws Exception {
Path root = Files.createTempDirectory("apdemo");
System.out.println("-- compiling with the annotation processor --");
var diagnostics = new StringWriter();
boolean ok = compile(root, SOURCES, diagnostics);
System.out.print(diagnostics);
System.out.println(" compilation succeeded: " + ok);
System.out.println("-- the generated source --");
Files.readAllLines(root.resolve("gen/gallery/Descriptions.java")).forEach(l -> System.out.println(" | " + l));
System.out.println("-- running the compiled program --");
try (var loader = new URLClassLoader(new URL[] { root.resolve("classes").toUri().toURL() })) {
loader.loadClass("gallery.Demo").getMethod("main", String[].class).invoke(null, (Object) new String[0]);
System.out.println(" @Describe kept in class file: "
+ (loader.loadClass("gallery.Tile").getAnnotations().length > 0) + " (SOURCE retention)");
}
System.out.println("-- a processor can report errors --");
Path root2 = Files.createTempDirectory("apdemo");
var bad = new LinkedHashMap<String, String>();
bad.put("gallery/Describe.java", SOURCES.get("gallery/Describe.java"));
bad.put("gallery/Bad.java", """
package gallery;
@Describe public class Bad {
@Describe public int scaled(int factor) { return factor; }
}
""");
var diag2 = new StringWriter();
boolean ok2 = compile(root2, bad, diag2);
System.out.print(diag2.toString().lines().filter(l -> l.contains("ERROR")).findFirst().orElse("") + "\n");
System.out.println(" compilation succeeded: " + ok2);
for (Path r : List.of(root, root2))
try (var walk = Files.walk(r)) { walk.sorted(Comparator.reverseOrder()).forEach(p -> p.toFile().delete()); }
}
}
-- compiling with the annotation processor --
[processor] round 1: annotations=[gallery.Describe], root elements=[gallery.Demo, gallery.Describe, gallery.Pixel, gallery.Tile]
[processor] round 2: annotations=[], root elements=[gallery.Descriptions]
[processor] round 3: annotations=[], root elements=[], last round
compilation succeeded: true
-- the generated source --
| // Generated by DescribeProcessor. Do not edit.
| package gallery;
| @javax.annotation.processing.Generated("DescribeProcessor")
| public final class Descriptions {
| public static String describe(gallery.Pixel obj) {
| var parts = new java.util.StringJoiner(", ", "{", "}");
| parts.add(describe(obj.getX()));
| parts.add(describe(obj.getY()));
| return parts.toString();
| }
| public static String describe(gallery.Tile obj) {
| var parts = new java.util.StringJoiner(", ", "Tile{", "}");
| parts.add(describe(obj.getCorner()));
| parts.add("width=" + describe(obj.getWidth()));
| parts.add("height=" + describe(obj.getHeight()));
| return parts.toString();
| }
| public static String describe(Object obj) { return String.valueOf(obj); }
| }
-- running the compiled program --
Tile{{3, 7}, width=16, height=9}
@Describe kept in class file: false (SOURCE retention)
-- a processor can report errors --
[processor] round 1: annotations=[gallery.Describe], root elements=[gallery.Bad, gallery.Describe]
[processor] round 2: annotations=[], root elements=[], last round
[javac] ERROR: @Describe methods must not have parameters
compilation succeeded: false
Common questions
Why did my annotation processor stop running after upgrading the JDK?
Since JDK 23, javac no longer runs processors it merely finds on the class path. Put them on the processor path (--processor-path, or annotationProcessorPaths in Maven), name them with -processor, or pass -proc:full to restore the old behavior.
Can an annotation processor add methods to an existing class?
No. The official API can only create new files. Lombok modifies the class by using internal compiler APIs, which is why it needs updates for new JDK versions. Records often remove the need for generated getters, equals and toString.
How do I report an error from a processor?
Call processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, message, element). The compiler shows it as a normal compile error at the element's location, and compilation fails.
Why do I get "Attempt to recreate a file" errors?
process runs once per round, and later rounds may get an empty set of annotations. If the processor creates the same file again, the Filer refuses. Generate each file only once, for example only when the annotation set isn't empty.
What popular libraries are annotation processors? MapStruct, Dagger, Immutables, AutoValue, Micronaut and Hibernate's JPA metamodel generator, among others. They generate code at compile time, so they need no runtime reflection.
API reference
javax.annotation.processing
| Type / method | Description |
|---|---|
AbstractProcessor | convenient base class; processingEnv gives access to the environment |
@SupportedAnnotationTypes, @SupportedSourceVersion, @SupportedOptions | declare supported annotations, source level and -A options |
boolean process(Set<? extends TypeElement> annotations, RoundEnvironment env) | called once per round; returning true claims the annotations |
Set<? extends Element> RoundEnvironment.getElementsAnnotatedWith(TypeElement a) (or Class<? extends Annotation>) | elements carrying an annotation in this round |
boolean RoundEnvironment.processingOver(), Set<? extends Element> getRootElements() | last-round flag; this round's input types |
JavaFileObject Filer.createSourceFile(CharSequence name, Element... originating) | creates a new source file (createResource for other files) |
void Messager.printMessage(Diagnostic.Kind kind, CharSequence msg, Element e) | reports an error, warning or note at an element |
javax.lang.model
| Type / method | Description |
|---|---|
Element.getKind(), getSimpleName(), getEnclosedElements(), getModifiers() | inspect any element |
TypeElement.getQualifiedName(), getSuperclass(), getInterfaces() | class information |
ExecutableElement.getParameters(), getReturnType() | method information |
<A extends Annotation> A AnnotatedConstruct.getAnnotation(Class<A> type), getAnnotationsByType(Class<A>) | annotations as objects (needs the annotation class) |
List<? extends AnnotationMirror> getAnnotationMirrors(), Elements.getElementValuesWithDefaults(AnnotationMirror m) | annotations as compile-time data |
Summary
- Annotation processors run inside
javac, in rounds. They receive supported annotations and annotated elements, and may generate new source or resource files, which trigger another round. They can't modify existing sources. - Extend
AbstractProcessor, declare@SupportedAnnotationTypes, returnlatestSupported()fromgetSupportedSourceVersion, and do nothing when the annotation set is empty. - Analyze code with the language model API:
TypeElement,ExecutableElement,VariableElement,getEnclosedElements, andgetAnnotationorAnnotationMirrors. Write files with theFiler, and report problems with theMessager. - Since JDK 23, processors must be configured explicitly (
-processor,--processor-path,-proc:full, or build-tool settings). Use-XprintRoundsto debug. - Generated code is fast and type-checked. Lombok modifies compiler internals and is not standard, and records reduce the need for it.
Practice Questions
Why does the processor return early when the annotations set is empty?
process is called in every round. Later rounds, such as the one processing the generated Descriptions.java, contain no @Describe annotations. Without the early return, the processor would try to create Descriptions again, which is an error, because a file can only be created once per compilation.
Can an annotation processor add a toString method directly to the annotated class? What does it do instead?
No. Processors may only create new files, not modify existing source. The example generates a separate helper class Descriptions with static overloaded methods.
What is the compile-time counterpart of Class, Method and Field?
In javax.lang.model.element, TypeElement corresponds to Class, ExecutableElement to Method/Constructor, and VariableElement to Field/Parameter. They describe the program by the rules of the language rather than as loaded classes.
How should a processor report that an annotation was used incorrectly?
Call processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, message, element). The compiler shows a normal error at the element's source position and compilation fails. Don't throw an exception.
After upgrading to JDK 23, a project's generated classes are suddenly missing. What is a likely cause?
Since JDK 23, javac doesn't automatically run processors found on the class path. The processors must be configured explicitly, with -processor, --processor-path/annotationProcessorPaths or -proc:full.
Previous: Processing Java Annotations at Runtime with Reflection
Next: Java Bytecode Engineering: Modifying Class Files with ASM and Java Agents
Related reading
- Processing Java Annotations at Runtime with Reflection
- Java Built-in Annotations: @Override, @Deprecated, @SuppressWarnings and Meta-Annotations
- Defining Custom Java Annotations: @interface, Elements, Retention and Target
- Java Annotations Explained: Syntax, Uses and Where You Can Annotate
- Java Processes and ProcessBuilder: Running and Managing External Programs

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.