首页 > 其他 > 详细

2种方法改变String 值

时间:2019-01-31 16:13:26      阅读:178      评论:0      收藏:0      [点我收藏+]
    @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 值

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!