为什么注释字符串值没有实现?

shm*_*sel 19 java annotations constants string-interning

尽管重用字符串常量和字面值,以下代码段会打印4个不同的哈希码.为什么字符串值没有插入注释元素?

public class Foo {
    @Retention(RetentionPolicy.RUNTIME)
    @interface Bar {
        String CONSTANT = "foo";

        String value() default CONSTANT;
    }

    public static void main(String[] args) throws Exception {
        System.out.println(System.identityHashCode(Bar.CONSTANT));
        System.out.println(System.identityHashCode(Foo.class.getMethod("test1").getAnnotation(Bar.class).value()));
        System.out.println(System.identityHashCode(Foo.class.getMethod("test2").getAnnotation(Bar.class).value()));
        System.out.println(System.identityHashCode(Foo.class.getMethod("test3").getAnnotation(Bar.class).value()));
    }

    @Bar
    public void test1() {}

    @Bar("foo")
    public void test2() {}

    @Bar(Bar.CONSTANT)
    public void test3() {}
}
Run Code Online (Sandbox Code Playgroud)

Ari*_*rld 10

字符串文字是实习的,但注释需要解析,它们存储在字节数组中.如果你看一下课程,java.lang.reflect.Method你可以看到:

private byte[]              annotations;
private byte[]              parameterAnnotations;
private byte[]              annotationDefault;  
Run Code Online (Sandbox Code Playgroud)

还要看一下public Object getDefaultValue()同一个类的方法,看看如何调用AnnotationParser.流程一直持续到这里 AnnotationParser.parseConst并输入

case 's':
  return constPool.getUTF8At(constIndex);
Run Code Online (Sandbox Code Playgroud)

该方法ConstantPool.getUTF8At是本机方法的委托.你可以在这里看到本机实现getUFT8At的代码 .解析的常量永远不会被实现,并且永远不会从StringTable(其中字符串被实现)中检索.

我认为这可能是实施的选择.已经创建了Interning以在String文字之间进行更快速的比较,因此仅用于在方法实现中可用的实习文字.