I have a rough idea, but still would like to ask if anyone knows why String
constants provided as annotation defaults change identity even though they reference static constants.
To illustrate, why does this code prints true, true, false, false
.
@TestAnn
public class TestClass {
public static final String STRING_CONSTANT = "SHOULD_BE_CONSTANT";
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnn {
String value() default TestClass.STRING_CONSTANT;
}
public class OtherTestClass {
String NOT_EVEN_STATIC = TestClass.STRING_CONSTANT;
}
private void run() throws Exception {
System.out.println(STRING_CONSTANT == constantValue());
System.out.println(STRING_CONSTANT == new OtherTestClass().NOT_EVEN_STATIC);
String str1 = getClass().getAnnotation(TestAnn.class).value();
System.out.println(STRING_CONSTANT == str1);
String str2 = (String) TestAnn.class.getMethod("value").getDefaultValue();
System.out.println(STRING_CONSTANT == str2);
}
private String constantValue() {
return TestClass.STRING_CONSTANT;
}
public static void main(String[] args) throws Exception {
new TestClass().run();
}
}