2种方法改变String 值
Posted johnboy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2种方法改变String 值相关的知识,希望对你有一定的参考价值。
@Test public void test1() throws Exception { String s = "ttttttt"; Unsafe u = getUnsafeInstance (); Field valueInString = String.class.getDeclaredField ( "value" ); long offset = u.objectFieldOffset ( valueInString ); long base = u.arrayBaseOffset ( char[].class ); long scale = u.arrayIndexScale ( char[].class ); char[] values = (char[]) u.getObject ( s, offset ); u.putChar ( values, base + scale, ‘c‘ ); s = "ttttttt"; String s1= "ttttttt"; System.out.println ( "s:" + s ); System.out.println ( "s1:" + s1 ); } public static Unsafe getUnsafeInstance() throws Exception { Field unsafeStaticField = Unsafe.class.getDeclaredField ( "theUnsafe" ); unsafeStaticField.setAccessible ( true ); return (Unsafe) unsafeStaticField.get ( Unsafe.class ); }
@Test public void test2() throws Exception { String s = "eeee"; Field valueInString = String.class.getDeclaredField ( "value" ); valueInString.setAccessible ( true ); char[] chars ={‘a‘,‘c‘,‘c‘}; valueInString.set ( s, chars); System.out.println (s); String s1 = "eeee"; System.out.println (s1); }
以上是关于2种方法改变String 值的主要内容,如果未能解决你的问题,请参考以下文章