class WithPrivateFinalField {
private final String s = \"I’m totally safe\";
public String toString() {
return \"s = \" + s;
}
}
WithPrivateFinal
This
class WithPrivateFinalField {
private final String s = "I’m totally safe";
public String toString() {
return "s = " + s;
}
}
actually compiles like this:
class WithPrivateFinalField {
private final String s = "I’m totally safe";
public String toString() {
return "s = I’m totally safe";
}
}
That is, compile-time constants get inlined. See this question. The easiest way to avoid inlining is to declare the String like this:
private final String s = "I’m totally safe".intern();
For other types, a trivial method call does the trick:
private final int integerConstant = identity(42);
private static int identity(int number) {
return number;
}