码迷,mamicode.com
首页 > 其他好文 > 详细

2种方法改变String 值

时间:2019-01-31 16:54:14      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:system   ret   putc   string   stat   ring   oid   index   eee   

    @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 值

标签:system   ret   putc   string   stat   ring   oid   index   eee   

原文地址:https://www.cnblogs.com/JohnBoy/p/10342149.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!