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

What Are Retention Policies?

Understand how retention policies control where and when annotations are available during compilation and runtime.

What Are Retention Policies?

You'll learn how retention policies determine when and where your custom annotations remain accessible.

The Lifecycle Problem

When you create a custom annotation, Java needs to know how long to keep it around. Should it disappear after compilation? Should it be embedded in the .class file? Should it be available at runtime for reflection? This is what retention policies control.

Think of retention policies like different types of notes you might write: a sticky note for temporary reminders (discarded quickly), a file folder label (permanent but not always visible), or a digital document (accessible anytime you need it).

The Three Retention Policies

Java provides three retention levels via the RetentionPolicy enum:

  1. SOURCE: The annotation exists only in source code and is discarded by the compiler. Useful for tools that analyze code before compilation.

  2. CLASS: The annotation is recorded in the .class file but isn't available at runtime via reflection. This is the default if you don't specify. Useful for bytecode analysis tools.

  3. RUNTIME: The annotation is recorded in the .class file and available at runtime through reflection. Essential when frameworks need to read annotations during program execution (like @Override checking at compile time vs. custom annotations processed by frameworks).

Why This Matters

Without the right retention policy, your annotation won't be available when you need it. If you're building a framework that reads annotations reflectively (like in lessons 2380-2387), you must use RUNTIME retention—otherwise, your annotations vanish before your code can inspect them.

Key Takeaway: Retention policies control an annotation's lifespan—SOURCE (compile-time only), CLASS (in bytecode), or RUNTIME (accessible via reflection)—and choosing the right one ensures your annotations are available exactly when needed.