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);
    }

 

 

 

posted @ 2019-01-31 15:26  落叶飞尘  阅读(1223)  评论(0编辑  收藏  举报