Lesson 34: Annotations: Built-in & Custom

04 Aug 2026 1 min Swarnil Singhai

Annotations attach metadata to code that tools, frameworks, or the compiler can read — from @Override to Spring's @Autowired.

Real-time example

A test framework scans for a custom @RetryOnFailure(times=3) annotation and re-runs any test marked with it automatically.

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface RetryOnFailure {
    int times() default 1;
}
class PaymentTest {
    @RetryOnFailure(times = 3)
    void testFlakyGateway() { /* ... */ }
}

What's happening

@Retention(RUNTIME) is what makes the annotation visible via reflection at runtime — without it, a test runner couldn't detect it at all.

Frameworks like Spring and JUnit are built almost entirely on custom annotations plus reflection reading them.

Advertisement