2种方法改变String 值
生活随笔
收集整理的這篇文章主要介紹了
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 值的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: What happens when cl
- 下一篇: dnf卢芙松的圣者遗物是什么 卢芙松的圣