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

RetentionPolicy.RUNTIME Explained

Discover RUNTIME retention: annotations available via reflection during program execution.

RetentionPolicy.RUNTIME Explained

What You'll Learn

You'll discover how RUNTIME retention makes annotations available during program execution, enabling powerful runtime processing via reflection.

Understanding RUNTIME Retention

RetentionPolicy.RUNTIME is the most powerful retention level. When you annotate your annotation with @Retention(RetentionPolicy.RUNTIME), the annotation information is:

  • Retained in the compiled .class file
  • Loaded into the JVM at runtime
  • Accessible via reflection during program execution

This is fundamentally different from SOURCE (discarded after compilation) and CLASS (present in bytecode but not loaded into memory).

Why RUNTIME Matters

Think of RUNTIME retention like a sticky note that travels with your code and remains visible while the program runs. This allows frameworks, libraries, and your own code to inspect annotations and make dynamic decisions based on them.

When you use reflection to call getAnnotations(), isAnnotationPresent(), or getAnnotation() on a Class, Method, or Field, you're reading RUNTIME annotations. Without RUNTIME retention, reflection returns nothing—the annotation is invisible.

Common Use Cases

  • Frameworks: Spring's @Autowired, JPA's @Entity, JAX-RS's @Path all use RUNTIME retention
  • Serialization: Jackson's @JsonProperty guides runtime JSON processing
  • Testing: JUnit's @Test tells the test runner which methods to execute
  • Validation: Bean Validation's @NotNull is checked at runtime

Any annotation that needs to affect program behavior during execution requires RUNTIME retention.

Key Takeaway:
Use RetentionPolicy.RUNTIME when your annotation must be readable via reflection during program execution—this is essential for frameworks, runtime validation, and any dynamic annotation processing.