Java › Standard

Java annotation processing and generated source code

Follow javac annotation-processing rounds, register a JSR 269 processor with Gradle, and compare generated source with Lombok's AST changes.

Java annotation processing and generated source code

When a generated mapper disappears after a JDK upgrade, I start with the compiler and its annotation processor path. The standard annotation-processing API explains which tools generate files and where a tool such as Lombok takes a different approach.

The examples use Gradle, javac, and the Java 17–25 annotation processing model.

What happens in a javac processing round

JSR 269 lets a processor inspect source-level program elements and types through compiler interfaces. The processor receives matching annotations for a round and can use Filer to generate source, class, or resource files. New source can become the input to another round. When the compiler has no more generated input to process, it sends a final round.

flowchart TD
    SRC["javac reads sources"] --> ROUND["Processor receives annotations"]
    ROUND --> FILE["Filer writes new sources"]
    FILE -->|"More source"| ROUND
    ROUND -->|"No new input"| FINAL["Final round and class files"]

Annotations give the processor inputs. They do not by themselves make it run. The processor has to be registered and discovered on the annotation processor path. The standard model can read existing program elements. It does not expose an API for rewriting their original syntax trees.

Building a processor that generates metadata

The example declares @GenerateMetadata in its own module. The processor handles types marked with that annotation and generates a companion source file through Filer.createSourceFile().

1
2
3
4
5
6
7
8
9
10
11
12
// processor/src/main/java/com/example/apt/GenerateMetadata.java
package com.example.apt;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
public @interface GenerateMetadata {
}

The processor extends AbstractProcessor. It checks which elements it can act on, reads the source type information, writes the new Java file, and records diagnostic messages through Messager. Diagnostic messages should point to the annotated element so the application developer can fix the right source file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// processor/src/main/java/com/example/apt/MetadataProcessor.java
package com.example.apt;

import java.io.IOException;
import java.io.Writer;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Filer;
import javax.annotation.processing.Messager;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic;
import javax.tools.JavaFileObject;

@SupportedAnnotationTypes("com.example.apt.GenerateMetadata")
@SupportedSourceVersion(SourceVersion.RELEASE_21)
public class MetadataProcessor extends AbstractProcessor {

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        Filer filer = processingEnv.getFiler();
        Messager messager = processingEnv.getMessager();

        for (Element element : roundEnv.getElementsAnnotatedWith(GenerateMetadata.class)) {
            if (element.getKind() != ElementKind.CLASS) {
                messager.printMessage(
                        Diagnostic.Kind.ERROR,
                        "@GenerateMetadata can only be declared on a class.",
                        element
                );
                continue;
            }

            TypeElement typeElement = (TypeElement) element;
            String packageName = processingEnv.getElementUtils()
                    .getPackageOf(typeElement)
                    .getQualifiedName()
                    .toString();
            String className = typeElement.getSimpleName().toString();
            String generatedClassName = className + "Metadata";

            try {
                JavaFileObject file = filer.createSourceFile(packageName + "." + generatedClassName, typeElement);
                try (Writer writer = file.openWriter()) {
                    writer.write("package " + packageName + ";\n\n");
                    writer.write("public final class " + generatedClassName + " {\n");
                    writer.write("    public static final String TARGET = \"" + className + "\";\n");
                    writer.write("}\n");
                }
            } catch (IOException e) {
                messager.printMessage(Diagnostic.Kind.ERROR, "Could not generate source: " + e.getMessage(), element);
            }
        }
        return true;
    }
}

A processor may see more than one round. Use a repeatable generated filename and avoid recreating a file that has already been claimed. When generated code uses the originating type, check imports, visibility, and package naming as well as the processor logic.

Registering the processor and inspecting its output

The SPI descriptor tells the compiler which implementation to load. The application includes the annotations on its compile classpath and the processor on Gradle’s annotationProcessor configuration.

1
2
// processor/src/main/resources/META-INF/services/javax.annotation.processing.Processor
com.example.apt.MetadataProcessor
1
2
3
4
5
// app/build.gradle.kts
dependencies {
    compileOnly(project(":processor"))
    annotationProcessor(project(":processor"))
}

From Java 23 onward, javac no longer implicitly runs processors simply because they appear on the regular classpath. Explicit processor configurations make the build easier to understand and diagnose. Inspect the generated output under build/generated/sources/annotationProcessor/ after compilation. If the expected file is absent, check the processor path and the SPI registration before tracing the application itself.

Generated files and AST modification

QuestionMapStruct and typical QueryDSL processorsLombok
Main compiler interactionGenerate additional Java sources through standard APIsUses compiler-specific hooks to alter the original type’s representation
What can I inspect?New source files in the generated-source directoryCompiled output or Lombok’s delomboked source
Upgrade concernProcessor compatibility, source version, and discoveryThose concerns plus change in compiler internals and module access
IDE concernRecognize generated sourcesSupport the generated members while editing the original type
flowchart TD
    TYPES["Annotated types"] --> API["JSR 269 processor"]
    API --> NEW["Generated Java source"]
    TYPES --> LOMBOK["Lombok compiler integration"]
    LOMBOK --> UPDATE["Members added during compilation"]

When Lombok and MapStruct work on the same types, MapStruct needs to see the accessors Lombok supplies. Use the lombok-mapstruct-binding processor dependency when the integration requires it. A build that only works inside one IDE can still fail in Gradle or CI.

Checking a compiler upgrade

Run a clean build using the same JDK as CI. Check that the processor loads, the expected source was written, and the generated types compile against the project. If an annotation produces a diagnostic, confirm the error names the source element. For projects using Lombok, verify its supported JDK version before investigating a compiler-internal failure.

This post is licensed under CC BY 4.0 by the author.