Course contentsShow
← Java
Lesson 2453 of 2,87046. AnnotationsFree lesson

Compile-Time vs Runtime Annotation Processing

Learn the difference between compile-time processors and runtime reflection, and when each is appropriate.

Compile-Time vs Runtime Annotation Processing

You'll learn: When annotations should be processed during compilation versus at runtime, and how to choose the right approach.

Two Distinct Processing Moments

Annotations can be processed at two different times in your application's lifecycle:

  1. Compile-time processing: Happens while javac compiles your code (before any .class files run)
  2. Runtime processing: Happens while your application is executing (using reflection)

Think of it like cooking: compile-time processing is meal prep (chopping vegetables, preparing ingredients before cooking), while runtime processing is adjusting seasoning while the dish is already on the stove.

Compile-Time Processing

Compile-time processors (also called annotation processors) analyze your code during compilation. They can:

  • Generate new source files or resources
  • Validate code structure
  • Produce errors or warnings

When appropriate:

  • Code generation (avoiding manual boilerplate)
  • Enforcing architectural rules at build time
  • Creating configuration files from annotations
  • Example: Lombok, AutoValue, Dagger

These processors work with @Retention(SOURCE) or @Retention(CLASS) annotations and require no runtime overhead—the work is done before your application even runs.

Runtime Processing

Runtime processing uses reflection to read annotations while your application executes. This approach:

  • Reads annotations from classes, methods, and fields at runtime
  • Makes decisions dynamically based on annotation presence
  • Requires @Retention(RUNTIME)

When appropriate:

  • Dependency injection frameworks
  • Testing frameworks checking @Test annotations
  • Serialization customization
  • Dynamic behavior configuration
  • Example: JUnit, Spring, Jackson

The tradeoff: runtime processing adds overhead during execution but provides flexibility to inspect and react to annotations on-the-fly.

Key Takeaway: Use compile-time processing for code generation and validation (zero runtime cost), and runtime processing when you need dynamic behavior based on annotations during execution.