AbstractProcessor: A Convenient Base Class
You'll learn: How AbstractProcessor provides a ready-to-use foundation that eliminates boilerplate when implementing custom annotation processors.
The Challenge of Implementing Processor
In the previous lesson, you learned about the Processor interface—the contract every annotation processor must fulfill. However, implementing all of Processor's methods from scratch involves significant boilerplate code. Most processors only care about a few methods, yet you'd need to provide implementations for every single one.
Enter AbstractProcessor
AbstractProcessor is an abstract class from javax.annotation.processing that implements Processor with sensible defaults. Think of it as a helpful template: it handles the tedious setup work so you can focus on the actual annotation processing logic.
Instead of implementing seven methods of Processor, you typically only override:
process()— where your actual processing logic livesgetSupportedAnnotationTypes()— which annotations you handle (or use@SupportedAnnotationTypes)getSupportedSourceVersion()— which Java version you support (or use@SupportedSourceVersion)
The base class provides default implementations for initialization, option handling, and completion callbacks.
How It Simplifies Your Work
AbstractProcessor automatically:
- Stores the
ProcessingEnvironmentfor you (accessible viaprocessingEnv) - Returns
falseforisInitialized()untilinit()completes - Handles the completion lifecycle
You annotate your class and override just what you need:
@SupportedAnnotationTypes("com.example.MyAnnotation")
@SupportedSourceVersion(SourceVersion.RELEASE_11)
public class MyProcessor extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
// Your processing logic here
return false;
}
}
Key Takeaway: AbstractProcessor eliminates boilerplate by providing default implementations of the Processor interface, letting you focus on the process() method where your annotation handling logic belongs—typically requiring just one override instead of seven.