ReviseAlgo Logo

Annotations

Annotation Processing

Understand compile-time annotation processing and code generation (APT).

Interview: Tests compile-time vs runtime processing concepts, compiler hooks, and the round-based processing structure.

Last Updated: June 13, 2026 10 min read

Java provides the Annotation Processing Tool (APT) to intercept metadata during the compilation phase. Processors can generate new source files or trigger compilation errors.

Core Idea

Annotation processing hooks into javac compile stages to read elements and write auxiliary files.

Why It Matters

Power utilities like Lombok, MapStruct, and Dagger generate complex code at compile time, eliminating runtime reflection overhead.

Interview Lens

Expect questions on round-based compilation and how APT avoids runtime reflection overhead.

Round-Based Processing

Annotation processing runs in multiple rounds: 1. The compiler parses source files and identifies annotations. 2. Associated processors run and can generate new Java files. 3. If new files are generated, a new round begins to compile the new sources. 4. This continues until no new source files are generated.

Processors extend the AbstractProcessor class and declare their supported annotations via @SupportedAnnotationTypes.

Interview-Relevant Information

Q: Can an annotation processor modify existing source code files?
Answer: Standard annotation processing APIs only permit creating new files. They do not allow modifying existing source code. (Lombok modifies existing AST structures by using private compiler APIs, which is a hack that bypasses Java's standard specification).

Quick Checklist

How do compilation rounds work? Can standard processors modify existing class codes? If yes, you understand annotation processing.

Use Cases

Generating boilerplate object-mapping source files at build time (e.g. MapStruct).

Enforcing custom code constraints at compile time (e.g. verifying all entities have primary keys).

Common Mistakes

Assuming annotation processors run at runtime (they are exclusively compile-time structures).

Forgetting to register the processor under META-INF/services, causing it to be ignored during compilation.