String类的不可变性

我想对于一个JAVA初学者来说,刚开始找工作,面试时一定被问到过这样一个问题:String类与StringBuffer的区别。二者的最大区别就是String类是不可变的,而StringBuffer是可变的,就是可以在不新建一个StringBuffer对象的情况下改变其值,而String改变值的话,就会产生一个新的String对象。但是为什么呢?

我想可能也会有一些初学者和我一样,开始并没有深究这个问题,刚开始时通过看String类的源码知道String类被声明为final,从而自然地就觉得声明为final的String的值就是因此而是不可变的。其实却不是这样的。

final关键字修饰变量时表明该变量的值不可变(变量所存的值不可变,但如果这个变量存的是对象的地址,那指向的对象还是可以变的);修饰方法表示该方法不可被改写;修饰类时表明类是不可被继承的,并不会使其对象不可变。由此可见final关键字并不能使 String的值不可变,其实说String的值不可变,是因为String对外提供的方法里都是通过新建String对象来完成的,那么有没有办法在不新建String对象的情况下改变其值呢?

方法其实还是有的,下面就介绍一下几种能改变String对象值的方法。

1、        利用反射。获取String对象中value数组的值,进行修改,从而达到修改String对象值的目的。

2、        利用我前面博文中提到的Unsafe类。获取value数组的地址偏移量,再进行修改,从而达到修改String对象值的目的。

 

代码:

package other;

import java.lang.reflect.Field;

import sun.misc.Unsafe;

public class TestString
{

    public static Unsafe getUnsafe()
    {
        Field field;
        try
        {
            field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            Unsafe unsafe;
            unsafe = (Unsafe) field.get(null);
            return unsafe;
        }
        catch(NoSuchFieldException | SecurityException e)
        {
            e.printStackTrace();
            return null;
        }
        catch(IllegalArgumentException | IllegalAccessException e)
        {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 通过反射获取String类的value域,并通过value域获取对象的value数组的引用来修改其值来修改String的值
     * 
     * @Title: test1
     * @Description: TODO(这里用一句话描述这个方法的作用)
     * @param @throws NoSuchFieldException
     * @param @throws SecurityException
     * @param @throws IllegalArgumentException
     * @param @throws IllegalAccessException 设定文件
     * @return void 返回类型
     * @throws
     */
    public static void test1() throws NoSuchFieldException, SecurityException,
            IllegalArgumentException, IllegalAccessException
    {
        String str1 = "Hello World!";
        String str2 = "Hello World!";
        String str3 = new String("Hello World!");

        System.out.println("str1 == str2: " + (str1 == str2));
        System.out.println("str2 == str3: " + (str2 == str3));

        Field field = String.class.getDeclaredField("value");
        field.setAccessible(true);
        char[] chars = (char[]) field.get(str1);

        chars[6] = 'F';
        chars[7] = 'r';
        chars[8] = 'i';
        chars[9] = 'e';
        chars[10] = 'n';
        chars[11] = 'd';

        System.out.println("修改chars1的值后str1的值是: " + str1);
        System.out.println("修改chars1的值后str2的值是: " + str2);
        System.out.println("修改chars1的值后str3的值是: " + str3);
    }

    /**
     * 通过反射获取String类的value域,并通过value域获取对象的value数组的引用来修改其值来修改String的值
     * 
     * @Title: test1
     * @Description: TODO(这里用一句话描述这个方法的作用)
     * @param @throws NoSuchFieldException
     * @param @throws SecurityException
     * @param @throws IllegalArgumentException
     * @param @throws IllegalAccessException 设定文件
     * @return void 返回类型
     * @throws
     */
    public static void test2() throws NoSuchFieldException, SecurityException,
            IllegalArgumentException, IllegalAccessException
    {
        String str1 = "Hello World!";
        String str2 = "Hello World!";
        String str3 = new String("Hello World!");

        System.out.println("str1 == str2: " + (str1 == str2));
        System.out.println("str2 == str3: " + (str2 == str3));

        Field field = String.class.getDeclaredField("value");
        field.setAccessible(true);
        char[] chars = new char[] { 'H', 'e', 'l', 'l', 'o', ' ', 'F', 'r',
                'i', 'e', 'n', 'd' };
        field.set(str1, chars);

        System.out.println("调用Field的set方法后str1的值是: " + str1);
        System.out.println("调用Field的set方法后str2的值是: " + str2);
        System.out.println("调用Field的set方法后str3的值是: " + str3);
    }

    /**
     * @throws SecurityException 
     * @throws NoSuchFieldException 
     * 通过Unsafe类在不新建String对象的情况下改变String对象的值
     * 
     * @Title: test3
     * @Description: TODO(这里用一句话描述这个方法的作用)
     * @param 设定文件
     * @return void 返回类型
     * @throws
     */
    public static void test3() throws NoSuchFieldException, SecurityException
    {
        String str1 = "Hello World!";
        String str2 = "Hello World!";
        String str3 = new String("Hello World!");

        Unsafe unsafe = getUnsafe();
        if (unsafe == null)
        {
            return;
        }
        long offset = unsafe.objectFieldOffset(String.class.getDeclaredField("value"));
        
        char[] chars = new char[] { 'H', 'e', 'l', 'l', 'o', ' ', 'F', 'r',
                'i', 'e', 'n', 'd' };
        unsafe.putObject(str1, offset, chars);
        
        System.out.println("使用Unsafe修改后str1的值是: " + str1);
        System.out.println("使用Unsafe修改后str2的值是: " + str2);
        System.out.println("使用Unsafe修改后str3的值是: " + str3);
    }

    public static void main(String[] args) throws NoSuchFieldException,
            SecurityException, IllegalArgumentException, IllegalAccessException
    {
        System.out.println("test1()");
        test1();
        System.out.println();

        System.out.println("test2()");
        test2();
        System.out.println();

        System.out.println("test3()");
        test3();
        System.out.println();
    }
}


运行结果:

test1()
str1 == str2: true
str2 == str3: false
修改chars1的值后str1的值是: Hello Friend
修改chars1的值后str2的值是: Hello Friend
修改chars1的值后str3的值是: Hello Friend

test2()
str1 == str2: true
str2 == str3: false
调用Field的set方法后str1的值是: Hello Friend
调用Field的set方法后str2的值是: Hello Friend
调用Field的set方法后str3的值是: Hello Friend

test3()
使用Unsafe修改后str1的值是: Hello Friend
使用Unsafe修改后str2的值是: Hello Friend
使用Unsafe修改后str3的值是: Hello Friend



编程技术交流请加QQ群:点击链接加入群【Just Do IT】:https://jq.qq.com/?_wv=1027&k=478lBF3


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值