Immutability of Strings in Java

后端 未结 26 2365
不思量自难忘°
不思量自难忘° 2020-11-21 06:33

Consider the following example.

String str = new String();

str  = \"Hello\";
System.out.println(str);  //Prints Hello

str = \"Help!\";
System.out.println(s         


        
26条回答
  •  逝去的感伤
    2020-11-21 07:13

    For those wondering how to break String immutability in Java...

    Code

    import java.lang.reflect.Field;
    
    public class StringImmutability {
        public static void main(String[] args) {
            String str1 = "I am immutable";
            String str2 = str1;
    
            try {
                Class str1Class = str1.getClass();
                Field str1Field = str1Class.getDeclaredField("value");
    
                str1Field.setAccessible(true);
                char[] valueChars = (char[]) str1Field.get(str1);
    
                valueChars[5] = ' ';
                valueChars[6] = ' ';
    
                System.out.println(str1 == str2);
                System.out.println(str1);
                System.out.println(str2);           
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
    
        }
    }
    

    Output

    true
    I am   mutable
    I am   mutable
    

提交回复
热议问题