使用兩種方式修改String的值: java
1.反射 code
2.Unsafe get
代碼示例: it
import java.lang.reflect.Field; import org.junit.Test; import sun.misc.Unsafe; public class ModifyString { /** * 反射修改String * @throws Exception * 2014年9月23日 */ @Test public void testReflect() throws Exception{ String str="hello,world"; Field f=str.getClass().getDeclaredField("value"); f.setAccessible(true); char[] target=new char[]{'h','a'}; Field c=str.getClass().getDeclaredField("count"); c.setAccessible(true); c.set(str, target.length); f.set(str, new char[]{'h','a'}); System.out.println(str); } /** * Unsafe 修改String * @throws Exception * 2014年9月23日 */ @Test public void testUnsafe1() throws Exception{ String str="hello,world"; Field f=str.getClass().getDeclaredField("value"); f.setAccessible(true); long offset; Unsafe unsafe=getUnsafe(); offset=unsafe.arrayBaseOffset(char[].class); char[] arr=(char[])f.get(str); unsafe.putChar(arr, offset, 'a'); System.out.println(str); } /** * Unsafe 修改String * @throws Exception * 2014年9月23日 */ @Test public void testUnsafe2() throws Exception{ String str="hello,world"; Field f=str.getClass().getDeclaredField("value"); f.setAccessible(true); long offset; Unsafe unsafe=getUnsafe(); char[] nstr=new char[]{'1','2'}; offset=unsafe.objectFieldOffset(f); Object o=unsafe.getObject(str, offset); unsafe.compareAndSwapObject(str, offset, o, nstr); System.out.println(str); } public static Unsafe getUnsafe() throws Exception{ Field theUnsafeInstance = Unsafe.class.getDeclaredField("theUnsafe"); theUnsafeInstance.setAccessible(true); return (Unsafe) theUnsafeInstance.get(Unsafe.class); } }