What is the practical difference between RetentionPolicy.CLASS
and RetentionPolicy.RUNTIME
?
It looks like both are recorded into the bytecode and both may be accessed at the run-time anyway.
class file but are discarded during runtime. CLASS is the default retention policy in Java. RetentionPolicy. RUNTIME: The annotations annotated using the RUNTIME retention policy are retained during runtime and can be accessed in our program during runtime.
Enum valuesAnnotations are to be recorded in the class file by the compiler but need not be retained by the VM at run time. RetentionPolicy. RUNTIME. Annotations are to be recorded in the class file by the compiler and retained by the VM at run time, so they may be read reflectively. RetentionPolicy.
@Retention : Specifies whether the annotation metadata can be accessed at runtime by the application (will determine whether the compiled bytecode is affected).
Annotation is defined like a ordinary Java interface, but with an '@' preceding the interface keyword (i.e., @interface ). You can declare methods inside an annotation definition (just like declaring abstract method inside an interface). These methods are called elements instead.
both may be accessed at the run-time anyway.
That's not what the javadoc says:
RUNTIME: Annotations are to be recorded in the class file by the compiler and retained by the VM at run time, so they may be read reflectively.
CLASS: Annotations are to be recorded in the class file by the compiler but need not be retained by the VM at run time.
In practice, I'm not aware of any use-cases for CLASS
. It would only be useful if you wanted to read the bytecode programmatically, as opposed to via the classloader API, but that's a very specialised case, and I don't know why you wouldn't just use RUNTIME
.
Ironically, CLASS
is the default behaviour.
It looks like both are recorded into the bytecode and both may be accessed at the run-time anyway.
False for basic built-in annotation interfaces like getAnnotations
. E.g.:
import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.CLASS) @interface RetentionClass {} @Retention(RetentionPolicy.RUNTIME) @interface RetentionRuntime {} public static void main(String[] args) { @RetentionClass class C {} assert C.class.getAnnotations().length == 0; @RetentionRuntime class D {} assert D.class.getAnnotations().length == 1; }
so the only way to observe a RetentionPolicy.CLASS
annotation is by using a bytecode parser.
Another difference is that the Retention.CLASS
annotated class gets a RuntimeInvisible class attribute, while Retention.RUNTIME
annotations get a RuntimeVisible class attribute. This can be observed with javap
.
Examples on GitHub for you to play with.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With