Hey, mir ist gerade etwas aufgefallen:
Warum funktioniert das:
import java.lang.reflect.Field;
/**
*
* @author Andy
*/
public class MutableString {
@SuppressWarnings("CallToPrintStackTrace")
public static void main(String[] args) {
String s = "Ein Text!";
System.out.println("Vorher: " + s + "." + s.hashCode());
try {
Field field = s.getClass().getDeclaredField("value");
field.setAccessible(true);
System.out.println("Get: " + new String((char[])field.get(s)));
char[] array = "Ein anderer Text!".toCharArray();
field.set(s, array);
} catch (IllegalAccessException | IllegalArgumentException | NoSuchFieldException | SecurityException ex) {
ex.printStackTrace();
}
System.out.println("Nachher: " + s + "." + s.hashCode());
}
}
Aber das nicht:
import java.lang.reflect.Field;
/**
*
* @author Andy
*/
public class MutableString {
@SuppressWarnings("CallToPrintStackTrace")
public static void main(String[] args) {
final String s = "Ein Text!";
System.out.println("Vorher: " + s + "." + s.hashCode());
try {
Field field = s.getClass().getDeclaredField("value");
field.setAccessible(true);
System.out.println("Get: " + new String((char[])field.get(s)));
char[] array = "Ein anderer Text!".toCharArray();
field.set(s, array);
} catch (IllegalAccessException | IllegalArgumentException | NoSuchFieldException | SecurityException ex) {
ex.printStackTrace();
}
System.out.println("Nachher: " + s + "." + s.hashCode());
}
}
Wird bei ner final-Variable der Wert iwo gecached, oder wie entsteht diesen Phänomen?