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 值的主要内容,如果未能解决你的问题,请参考以下文章

有没有办法改变片段主题?

在第二种方法中,第二个微调器值没有改变

JAVA之AOP

3.给只读动画添加事件

有关java参数的两种传递机制

Kotlin - 如何将空值传递给片段 newInstance 方法?