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

Choosing the Right Retention Policy

Learn decision criteria for selecting SOURCE, CLASS, or RUNTIME based on your annotation's purpose.

Choosing the Right Retention Policy

What you'll learn: How to decide which retention policy—SOURCE, CLASS, or RUNTIME—best fits your annotation's intended purpose.

Decision Criteria

Now that you understand the three retention policies, the key question is: when does your annotation need to exist? The answer determines your choice:

Use SOURCE When:

  • Your annotation is only for the compiler or code generation tools
  • No bytecode inspection or runtime processing is needed
  • Examples: @Override, @SuppressWarnings
  • Benefit: Zero runtime footprint, smallest .class files

Use CLASS When:

  • You need bytecode analysis or manipulation without runtime overhead
  • Tooling will process .class files during build or deployment
  • Examples: bytecode optimizers, dependency injection preprocessors
  • Benefit: Available to tools, but invisible at runtime (moderate overhead)

Use RUNTIME When:

  • Your annotation must be read by running code via reflection
  • Frameworks need to discover and process annotations dynamically
  • Examples: @Test (JUnit), @Entity (JPA), custom validation annotations
  • Benefit: Maximum flexibility, but increases .class size and requires reflection

The Decision Tree

Ask yourself:

  1. Does running code need this? → Use RUNTIME
  2. Does bytecode tooling need this? → Use CLASS
  3. Is this just for compilation? → Use SOURCE

When in doubt, start with the most restrictive policy (SOURCE), then move to CLASS or RUNTIME only if you have a clear reason. This minimizes overhead and keeps your application lean.

Key Takeaway: Choose retention based on who needs your annotation and when: SOURCE for compile-time checks, CLASS for build-time tooling, RUNTIME for reflective framework processing.