Sub topic 16
Compile-time annotation processing: a brief overview
This chapter assumes you have read the earlier chapters on annotations, @Retention, and @Target. It also assumes you can compile and run Java from the command line.
What annotation processing does
Reflection reads annotations while the program runs. An annotation processor reads them while javac compiles the code. The compiler calls your processor, hands it a model of the source code, and lets it report errors or generate new source files.
Processors work on source elements: classes, methods, and fields. They do not load your classes, so there are no Class objects, no Method.invoke, and no setAccessible.
Runtime or compile time
| Concern | Runtime reflection | Annotation processor |
|---|---|---|
| When it runs | Program execution | Compilation |
| Errors appear | As exceptions in production | As compiler errors |
| Per-call cost | Lookup and access checks | None, since generated code is plain Java |
| Can see private members | Yes, with limits from modules | Yes, as source elements |
| Can change existing classes | Not by itself | No, it can only add new files |
Prefer a processor when a mistake can be caught before the program ships, or when you want to generate boilerplate such as builders or lookup tables. Prefer reflection when the types are only known at runtime.
A small processor
This example rejects @PublicOnly on any method that is not public. The annotation uses SOURCE retention, because only the compiler needs it.
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.METHOD)
public @interface PublicOnly {
}The processor extends AbstractProcessor. It uses the Messager to report problems against a specific element.
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.Modifier;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic;
@SupportedAnnotationTypes("PublicOnly")
@SupportedSourceVersion(SourceVersion.RELEASE_11)
public class PublicOnlyProcessor extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
for (TypeElement annotation : annotations) {
for (Element e : roundEnv.getElementsAnnotatedWith(annotation)) {
if (!e.getModifiers().contains(Modifier.PUBLIC)) {
processingEnv.getMessager().printMessage(
Diagnostic.Kind.ERROR,
"@PublicOnly requires a public method",
e);
}
}
}
return true;
}
}Now a class that breaks the rule:
public class Service {
@PublicOnly
void hidden() {
}
}Compile the annotation and processor first with processing switched off. Then compile Service with the processor enabled.
javac -proc:none PublicOnly.java PublicOnlyProcessor.java
javac -cp . -processor PublicOnlyProcessor Service.javaThe second command fails with an error that points at hidden().
Common errors
- Compiling the processor and the code it processes in one step. The processor must already be compiled.
- Forgetting that a processor runs in rounds. If it generates a source file,
javacprocesses that file in a new round. - Expecting to edit an existing class. The standard API only creates new files through
Filer. - Using
RUNTIMEretention for annotations only a processor reads.SOURCEis enough and keeps class files smaller.
For real projects, register a processor with a META-INF/services/javax.annotation.processing.Processor file so javac finds it without -processor.
Exercise
A team wants to fail the build when a field marked @Id is not declared private. Should they use runtime reflection or an annotation processor, and what retention should @Id use if only that check reads it?
Show answer
Use an annotation processor, because the check depends only on source declarations and a compiler error is better than a failure in production. If only the processor reads @Id, RetentionPolicy.SOURCE is enough.