Sub topic 16
Compile-time annotation processing: a brief overview
This chapter assumes you can write and apply a custom annotation, choose a @Retention policy, and read annotations with reflection. You should also be able to compile and run Java from the command line with javac and java. The chapter shows a different place to use annotations: the compiler itself, before any program runs.
What annotation processing is
Reflection reads annotations while the program runs. Annotation processing reads them while javac compiles. A processor is a Java class that the compiler loads and calls during compilation. It receives a model of the source code being compiled. It can report errors and warnings, and it can generate new source files, which javac then compiles in the same run.
The API is standardized (JSR 269) and lives in two packages:
javax.annotation.processingholdsAbstractProcessor,RoundEnvironment,Filer, andMessager.javax.lang.modelholds the language model:Element,TypeElement,ExecutableElement,TypeMirror, and related types.
With the standard API, a processor cannot change an existing class. It can only add new files and emit diagnostics. This limit makes processors predictable, and it shapes how they are used.
Where processing fits in compilation
The compiler parses your sources, then runs processors in rounds. In each round, a processor sees the annotated elements. If it generates new source files, javac parses them and starts another round with those files as input. Rounds continue until no new files appear. A final round then runs with processingOver() returning true. Only after that does javac produce class files.
Retention and processors
An annotation that only a processor needs can use RetentionPolicy.SOURCE. The compiler discards it after compilation, so it adds nothing to the class file. Processors see annotations in any retention policy, because they run before the class file is written. CLASS and RUNTIME annotations are also visible to processors.
A complete example
The example generates a class that describes the fields of any class marked @AutoDescribe. It has four source files, all in the package demo, in a directory named demo.
The annotation, in demo/AutoDescribe.java:
package demo;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.TYPE)
public @interface AutoDescribe {
}The processor, in demo/DescribeProcessor.java:
package demo;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
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.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("demo.AutoDescribe")
@SupportedSourceVersion(SourceVersion.RELEASE_11)
public class DescribeProcessor extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
for (Element element : roundEnv.getElementsAnnotatedWith(AutoDescribe.class)) {
if (element.getKind() != ElementKind.CLASS) {
processingEnv.getMessager().printMessage(
Diagnostic.Kind.ERROR,
"@AutoDescribe can only be applied to classes",
element);
continue;
}
try {
generate((TypeElement) element);
} catch (IOException e) {
processingEnv.getMessager().printMessage(
Diagnostic.Kind.ERROR,
"Could not write source: " + e.getMessage(),
element);
}
}
return true;
}
private void generate(TypeElement type) throws IOException {
String pkg = processingEnv.getElementUtils()
.getPackageOf(type).getQualifiedName().toString();
String simple = type.getSimpleName().toString();
List<String> parts = new ArrayList<>();
for (Element member : type.getEnclosedElements()) {
if (member.getKind() == ElementKind.FIELD) {
parts.add(member.getSimpleName() + ":" + member.asType());
}
}
String description = simple + " " + String.join(", ", parts);
JavaFileObject file = processingEnv.getFiler()
.createSourceFile(pkg + "." + simple + "Describer", type);
try (Writer out = file.openWriter()) {
out.write("package " + pkg + ";\n");
out.write("public final class " + simple + "Describer {\n");
out.write(" public static String describe() {\n");
out.write(" return \"" + description + "\";\n");
out.write(" }\n");
out.write("}\n");
}
}
}The annotated class, in demo/Person.java:
package demo;
@AutoDescribe
public class Person {
String name;
int age;
}A caller, in demo/Main.java:
package demo;
public class Main {
public static void main(String[] args) {
System.out.println(PersonDescriber.describe());
}
}Main refers to PersonDescriber, which exists in no source file you wrote. The processor creates it during the build. The processor must be compiled before it can run, so build in two steps:
mkdir out
javac -proc:none -d out demo/AutoDescribe.java demo/DescribeProcessor.java
javac -cp out -processor demo.DescribeProcessor -d out demo/Person.java demo/Main.java
java -cp out demo.MainThe first command compiles the annotation and processor with processing turned off. The second runs the processor while compiling Person and Main. The last command prints:
Person name:java.lang.String, age:intThe pieces of a processor
@SupportedAnnotationTypeslists the annotation names the processor wants. Names are fully qualified strings. Use"*"only if you truly need every annotation.@SupportedSourceVersionstates the newest language version the processor knows. If the compiler runs at a newer version, it prints a warning. OverridinggetSupportedSourceVersion()to returnSourceVersion.latestSupported()avoids the warning.processis called once per round. The return value says whether the processor claims the annotations, so later processors skip them. Returningtruefor annotations only your processor handles is the usual choice.Filercreates new source, class, or resource files. Passing the originating element, as the example does, lets build tools track which output came from which input.Messagerreports diagnostics. AnERRORmessage fails the build and points at the offending element in the source, which is how validation at compile time works.ElementandTypeMirrormodel declarations and types. They are notjava.lang.reflectobjects. The annotated classes may not even be compiled yet, so you cannot callClass.forNameon them.
Registering a processor
Passing -processor on the command line works for experiments. For a library, javac finds processors through the service loader. Add a file at META-INF/services/javax.annotation.processing.Processor inside the processor's jar. The file contains one line, the fully qualified class name:
demo.DescribeProcessorAny project that puts that jar on its classpath, or on -processorpath, then runs the processor automatically. Build tools usually offer a separate setting for processor jars, so that the processor does not end up in the application's runtime dependencies.
Processing compared with runtime reflection
| Aspect | Runtime reflection | Compile-time processing |
|---|---|---|
| When it runs | While the program runs | While `javac` runs |
| Cost at run time | Lookups, access checks, slower calls | None, the output is ordinary code |
| Errors found | At run time, often late | At build time, with source locations |
| Can read private members | Yes, with `setAccessible` and module permission | Sees declarations, but does not execute code |
| Can see values and objects | Yes | No, only declarations and types |
| Can change existing classes | Only through proxies and similar tools | Not with the standard API |
| Works without a rebuild | Yes | No, requires recompilation |
Processing suits work that depends only on declarations: generating builders, mappers, serializers, or lookup tables, and rejecting misuse early. Reflection suits work that depends on actual objects, such as validating the values in a particular instance. Many libraries combine them. A processor generates the code that would otherwise need reflection, which also helps ahead-of-time compilation and tools that remove unused code.
Common errors and limits
- The processor never runs. The usual causes are a missing
META-INF/servicesentry, the processor jar not on the processor path, or-proc:noneleft on the command line. - Compiling the processor and its users in one step. The processor class has to exist already when
javacstarts. Build it first or place it in a separate module. - Generating files in the final round. Files created after
processingOver()becomestrueare not processed, and the compiler warns about them. Generate whileprocessingOver()isfalse. - Creating the same file twice.
Filerthrows if you create a type that already exists. BecausegetElementsAnnotatedWithreturns elements for the current round only, this mostly happens when one processor reacts to its own output. - Assuming reflection works on the model. Calling
getAnnotation(...)on an element works, but reading aClassvalue from an annotation throwsMirroredTypeException. Use theTypeMirrorcarried by that exception, or read annotation mirrors instead. - Rewriting classes. The standard API cannot edit existing code. Tools that appear to do so, such as Lombok, use compiler internals that are not part of the specification and can break on new JDK versions.
Exercise
Why does the example mark @AutoDescribe with RetentionPolicy.SOURCE, and why can the processor still see it?
Show answer
Processors run inside the compiler, before class files are written, so they can see annotations of any retention. SOURCE retention is enough because nothing needs the annotation at run time, and it keeps the annotation out of the class file.
Exercise
A teammate wants to validate at build time that no field annotated @NotBlank has a non-String type. Would you use a processor or runtime reflection? Name one thing a processor cannot check here.
Show answer
A processor fits, because field types are declarations the compiler already knows, and an ERROR message pointing at the field fails the build early. A processor cannot check whether a field's value is blank, because it never sees objects or values at run time. That check needs reflection, or generated code that runs at run time.