Compile-Time Annotation Processors
Write an AbstractProcessor to generate source files or validate code at compile time.
What Are Annotation Processors?
Annotation processors (APT — Annotation Processing Tool) run during compilation. They inspect source code annotations and can generate new source files, resource files, or raise compiler errors/warnings.
AbstractProcessor: The Base Class
Extend javax.annotation.processing.AbstractProcessor. Override process() to handle annotated elements. Declare supported annotations and Java source version.
import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.*;
@SupportedAnnotationTypes("com.example.GenerateBuilder")
@SupportedSourceVersion(SourceVersion.RELEASE_17)
public class BuilderProcessor extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
for (Element e : roundEnv.getElementsAnnotatedWith(GenerateBuilder.class)) {
generateBuilder((TypeElement) e);
}
return true;
}
private void generateBuilder(TypeElement cls) { /* generate source */ }
}All lessons in this course
- Defining Annotations: Elements and Defaults
- Retention Policies and Target Types
- Runtime Annotation Processing
- Compile-Time Annotation Processors