effect of changing String using reflection

后端 未结 7 606
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-03 17:54

As we all know, String is immutable in java. however, one can change it using reflection, by getting the Field and setting access level. (I know it is unadvised, I am not pl

7条回答
  •  生来不讨喜
    2020-12-03 18:12

    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
    

提交回复
热议问题