Use Cases for RUNTIME Retention
What you'll learn: You'll discover how frameworks and libraries leverage RUNTIME retention to read annotations while your program is running.
Why Read Annotations at Runtime?
When you set retention to RUNTIME, annotations become part of the compiled class and remain accessible while your program executes. This enables frameworks to inspect your code's metadata and make decisions dynamically—essentially letting them "read the instructions you left" through annotations.
Real-World Framework Examples
Dependency Injection (Spring, CDI):
Frameworks like Spring read annotations such as @Autowired, @Component, or @Inject at runtime to automatically wire objects together. The framework scans your classes, finds these annotations using reflection (getAnnotations(), isAnnotationPresent()), and injects dependencies without you writing factory code.
ORM Tools (Hibernate, JPA):
Object-Relational Mapping frameworks read annotations like @Entity, @Table, @Column at runtime to map Java objects to database tables. When you persist an object, Hibernate inspects these annotations reflectively to generate SQL statements dynamically.
REST Frameworks (JAX-RS, Spring MVC):
Web frameworks scan methods for @GET, @POST, @Path annotations at runtime to route HTTP requests to the correct handler methods. The framework builds its routing table by reading these annotations when the application starts.
Validation (Bean Validation):
Libraries read annotations like @NotNull, @Size, @Email at runtime to validate object state dynamically. Validators use reflection to check field values against constraints defined in annotations.
The Pattern
All these frameworks follow the same pattern: use reflection APIs to discover annotated elements, read annotation values, and perform framework-specific logic based on that metadata.
Key Takeaway: RUNTIME retention powers modern Java frameworks by enabling them to read your annotations reflectively, allowing for configuration through metadata rather than explicit code—the foundation of dependency injection, ORM, REST routing, and validation libraries.