RetentionPolicy CLASS vs. RUNTIME

匿名 (未验证) 提交于 2019-12-03 01:29:01

问题:

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.

回答1:

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.



回答2:

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.



回答3:

Annotations with Retention Policy CLASS and RUNTIME are accessible from class byte code. We need to use a byte code manipulation library(e.g. ASM) to access the Annotations available in byte code.

Simple example here - http://bethecoder.com/applications/tutorials/java/annotations/class-and-runtime-retention-policy.html



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!