RetentionPolicy.SOURCE Explained
What you'll learn: How RetentionPolicy.SOURCE causes annotations to be discarded by the compiler, making them useful only during source code processing.
The Compiler's "Delete After Reading" Policy
When you annotate an annotation with @Retention(RetentionPolicy.SOURCE), you're telling Java: "This annotation is only for source code analysis—throw it away after compilation."
These annotations never make it into the .class file. The compiler reads them, processes them if needed, and then discards them completely. They're invisible at runtime and won't show up when you use reflection to read annotations.
When SOURCE Retention Makes Sense
Think of SOURCE annotations like sticky notes on a draft document. They're helpful during the writing process but don't need to be on the final printed copy.
Common use cases:
- Code generation tools that scan source files before compilation
- Documentation generation like JavaDoc tags
- Compile-time verification where the annotation's job is done once the compiler validates something
- IDE hints that help developers but don't affect runtime behavior
@Override is actually a SOURCE retention annotation—the compiler checks that you're properly overriding a method, then throws the annotation away. By runtime, it's served its purpose.
The Key Difference
Unlike CLASS or RUNTIME retention, SOURCE annotations are completely gone after compilation. You cannot read them reflectively, and they add zero bytes to your compiled .class files.
Key Takeaway: Use RetentionPolicy.SOURCE for annotations that serve their purpose during source code processing and don't need to survive compilation—the compiler discards them completely, keeping them out of .class files and making them unavailable at runtime.