Course contentsShow
← Java
Lesson 2379 of 2,87045. Reflection APIFree lesson

Annotation Retention and Runtime Availability

Understanding which annotations are available at runtime via RUNTIME retention policy and why SOURCE/CLASS annotations cannot be read.

Annotation Retention and Runtime Availability

You'll learn: Why some annotations are visible at runtime while others disappear during compilation, and how retention policies control this behavior.

The Three Retention Policies

When you define a custom annotation in Java, you specify its retention policy using @Retention. This policy determines how long the annotation information survives:

  • SOURCE: Annotation exists only in source code; discarded by the compiler
  • CLASS: Annotation is compiled into the .class file but not loaded into the JVM at runtime
  • RUNTIME: Annotation is compiled into the .class file and available at runtime via reflection

Why Retention Matters for Reflection

The Reflection API can only read annotations marked with RetentionPolicy.RUNTIME. Think of it like security clearance levels: if an annotation has SOURCE or CLASS retention, it's been "cleared away" by the time your running program tries to inspect it.

SOURCE annotations are meant for compile-time tools (like @Override or @SuppressWarnings)—they guide the compiler but serve no purpose afterward.

CLASS annotations persist in bytecode for bytecode analysis tools but aren't loaded into memory when the JVM runs your program.

RUNTIME annotations are the only ones your reflection code can access using methods like getAnnotation(), getDeclaredAnnotations(), or isAnnotationPresent().

Practical Impact

If you try to reflectively read a @SOURCE or @CLASS annotation at runtime, you'll get null or an empty array—the information simply isn't there. Only @RUNTIME annotations survive the journey from source → bytecode → running JVM.

Key Takeaway:
Only annotations with @Retention(RetentionPolicy.RUNTIME) can be read via reflection; SOURCE and CLASS annotations are invisible at runtime because they're discarded before or during JVM loading.