Retention Policy for Annotations in Java
As we all know that Java Annotations are used to provide metadata for our code, typically used for the following purposes
- Compile-Time Instructions
- Build-Time Instructions
- Run-Time Instructions
I am sure all of us must have used one or more of the built-in Java annotations like @Deprecated, @Override, @SuppressWarnings. But when it comes to creating our own annotation, say something like this
@interface WakeUpTheDevil {
String enchanchment();
int numberOfSacrifices();
}
By Default, this annotation is stored in the .class file & not available at the runtime. This is because of the default Retention Policy - RetentionPolicy.CLASS
What if we want our annotation to be available at runtime? Well, this is Java that we are talking about, Java allows us to specify this using RetentionPolicy.RUNTIME, which signals the compiler & the JVM that this annotation should be available via reflection at runtime.
But wait..what if I don’t want it at runtime, but I don’t want to pollute my .class file either? Java provides RetentionPolicy.SOURCE, which makes the annotation available only in the source code and not in the .class file or at runtime. Such annotations are used with build-tools that scan the file.