Annotation Processor
Definition
An annotation processor is a plugin that javac runs while it compiles your code. It inspects Java annotations on source elements and can validate them or generate new .java files, which the compiler then compiles in a later round. Processors live in javax.annotation.processing and usually extend AbstractProcessor. Because the work happens at compile time, the generated code has zero extra runtime cost compared with a reflection scan after startup.
Key Takeaways
- Processors run inside the compiler, not inside your finished application.
- SOURCE retention is the usual choice when the annotation exists only to drive generation or checks.
- You register a processor with
META-INF/services/javax.annotation.processing.Processoror a tool such as AutoService. - Lombok, MapStruct, Dagger, and Android Room are the processors most developers meet every day.
How It Works
javacloads processors and matches them to annotation types they claim to support.- Each round,
processreceives the elements that carry those annotations. - A processor may write new source. The compiler compiles it and starts another round until nothing new is produced.
- Kotlin projects often reach Java processors through kapt, or skip Java stubs with KSP.
Where It Is Used
- MapStruct generates mapper implementations from
@Mapperinterfaces. - Dagger generates the dependency injection graph from
@Injectand@Module. - Room generates SQLite bindings from
@Daoand@Entityduring the Android Gradle build.