【发布时间】:2016-10-17 14:47:47
【问题描述】:
以下 sn-p 打印 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() {}
}
【问题讨论】:
-
注解字符串字面量不是代码的一部分,也不受代码中字符串字面量规则的约束,因此没有理由将它们汇集起来。
标签: java annotations constants string-interning