001package algs12;
002import stdlib.*;
003import java.lang.reflect.Field;
004/* ***********************************************************************
005 *  Compilation:  javac MutableString.java
006 *  Execution:    java MutableString
007 *
008 *  Shows that Strings are mutable if you allow reflection.
009 *
010 *************************************************************************/
011
012public class XMutableString {
013
014        public static void main(String[] argv) {
015                String s = "Immutable";
016                String t = "Notreally";
017
018                mutate(s, t);
019                StdOut.println(t);
020
021                // strings are interned so this doesn't print "Immutable"
022                StdOut.println("Immutable");
023        }
024
025        // change the first min(|s|, |t|) characters of s to t
026        public static void mutate(String s, String t) {
027                try {
028                        Field val = String.class.getDeclaredField("value");
029                        Field off = String.class.getDeclaredField("offset");
030                        val.setAccessible(true);
031                        off.setAccessible(true);
032                        int offset   = off.getInt(s);
033                        char[] value = (char[]) val.get(s);
034                        for (int i = 0; i < Math.min(s.length(), t.length()); i++)
035                                value[offset + i] = t.charAt(i);
036                }
037                catch (Exception e) { e.printStackTrace(); }
038        }
039
040}