effect of changing String using reflection

After compilation some strings may refer to the one instance, so, you will edit more than you want and never know what else are you editing.

public static void main(String args[]) throws Exception {
    String s1 = "Hello"; // I want to edit it
    String s2 = "Hello"; // It may be anywhere and must not be edited
    Field f = String.class.getDeclaredField("value");
    f.setAccessible(true);
    f.set(s1, "Doesn't say hello".toCharArray());
    System.out.println(s2);
}

Output:

Doesn't say hello

Leave a Comment