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:
-
SOURCE: The annotation exists only in source code and is discarded by the compiler. Useful for tools that analyze code before compilation.
-
CLASS: The annotation is recorded in the
.classfile but isn't available at runtime via reflection. This is the default if you don't specify. Useful for bytecode analysis tools. -
RUNTIME: The annotation is recorded in the
.classfile and available at runtime through reflection. Essential when frameworks need to read annotations during program execution (like@Overridechecking 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.