String 真的不可变吗?

为什么 String 类不可变

  1. final修饰符: String类被声明为final,这意味着它不能被继承。因此,无法创建String的子类来修改其行为。
  2. 私有字符数组(char[]): String类内部使用私有的字符数组来存储字符串的内容。这个字符数组是final的,即它的引用不能被修改。一旦字符串被创建,它的内容就不能被更改。
  3. 不提供可变方法: String类没有提供用于修改字符串的方法。例如,没有类似于setCharAt(int index, char ch)的方法,而是提供了返回新字符串的方法,比如substring()concat()等。

有没有办法直接修改 String 对象的值而不是 重新创建一个字符串对象

其实是有的,Java 提供了反射机制是可以获取到私有的字段并且设置其字段值的。

关于Java反射的介绍

直接修改字符串的值,会重新创建一个字符串对象

java 复制代码
    public void test01() throws Exception {
        Field value = String.class.getDeclaredField("value");
        value.setAccessible(true);
        char[] chars = null;
        String str = "hhhhh";
        chars = (char[]) value.get(str);
        // identityHashCode() 基于对象地址返回哈希码
        System.out.println("字符串地址:" + System.identityHashCode(str) +
                " 值:" + str +
                " value地址:" + System.identityHashCode(chars));
        str = "hello world";
        chars = (char[]) value.get(str);
        System.out.println("字符串地址:" + System.identityHashCode(str) +
                " 值:" + str +
                " value地址:" + System.identityHashCode(chars));
    }

// 输出
字符串地址:721748895 值:hhhhh value地址:1642534850
字符串地址:1724731843 值:hello world value地址:1305193908

使用反射直接修改字符串数组的值

java 复制代码
public void test02() throws Exception {
        Field value = String.class.getDeclaredField("value");
        value.setAccessible(true);
        char[] chars = null;

        String str = "hello world";
        chars = (char[]) value.get(str);
        System.out.println("字符串地址:" + System.identityHashCode(str) +
                " 值:" + str +
                " value地址:" + System.identityHashCode(chars));

        for (int i = 0; i < chars.length; i++) {
            chars[i] = 'a';
        }

        chars = (char[]) value.get(str);
        System.out.println("字符串地址:" + System.identityHashCode(str) +
                " 值:" + str +
                " value地址:" + System.identityHashCode(chars));
    }
// 输出
字符串地址:721748895 值:hello world value地址:1642534850
字符串地址:721748895 值:aaaaaaaaaaa value地址:1642534850

使用反射修改字段的值

java 复制代码
    public void test03() throws Exception {
        Field value = String.class.getDeclaredField("value");
        value.setAccessible(true);
        char[] chars = null;

        String str = "hello world";
        chars = (char[]) value.get(str);
        System.out.println("字符串地址:" + System.identityHashCode(str) +
                " 值:" + str +
                " value地址:" + System.identityHashCode(chars));

        char[] tmp = {'1','2','3'};
        value.set(str,tmp);
        chars = (char[]) value.get(str);
        System.out.println("字符串地址:" + System.identityHashCode(str) +
                " 值:" + str +
                " value地址:" + System.identityHashCode(chars));
    }
// 输出
字符串地址:721748895 值:hello world value地址:1642534850
字符串地址:721748895 值:123 value地址:1724731843

当然这种直接修改char[]数组,绕过了String类安全机制的操作是不推荐的,因为它可能导致程序在运行时产生不可预测的行为,并且可能破坏其他代码对字符串不可变性的依赖。

使用反射修改违背了 Java 语言中字符串不可变性的设计原则。在实际开发中,最好遵循这个设计原则,以确保代码的可靠性和可维护性。如果需要可变的字符串,建议使用StringBuilderStringBuffer类。

相关推荐
蓝澈112119 分钟前
迪杰斯特拉算法之解决单源最短路径问题
java·数据结构
Kali_0726 分钟前
使用 Mathematical_Expression 从零开始实现数学题目的作答小游戏【可复制代码】
java·人工智能·免费
rzl0238 分钟前
java web5(黑马)
java·开发语言·前端
jingling5551 小时前
面试版-前端开发核心知识
开发语言·前端·javascript·vue.js·面试·前端框架
guojl1 小时前
深度解读jdk8 HashMap设计与源码
java
guojl1 小时前
深度解读jdk8 ConcurrentHashMap设计与源码
java
m0_687399841 小时前
写一个Ununtu C++ 程序,调用ffmpeg API, 来判断一个数字电影的视频文件mxf 是不是Jpeg2000?
开发语言·c++·ffmpeg
爱上语文1 小时前
Redis基础(5):Redis的Java客户端
java·开发语言·数据库·redis·后端
A~taoker1 小时前
taoker的项目维护(ng服务器)
java·开发语言
萧曵 丶1 小时前
Rust 中的返回类型
开发语言·后端·rust