0
点赞
收藏
分享

微信扫一扫

AFCI 应用笔记三、使用 mlflow 管理模型

静鸡鸡的JC 04-09 11:01 阅读 1
javalinux

String中的值真的不能修改吗?

前沿

首先string本质上使用private final char value[] 作为数据结构,因为使用了final表示是不可变的。但对于编程而言没有绝对的安全,其实利用反射可以绕过权限直接修改string的值。

反射通过绕过private权限直接修改final值从而实现的。

代理示例

String str = "修改前的字符串变量取值";
        System.out.println(str + "   地址:" + System.identityHashCode(str));
        System.out.println("旧:" + " 地址: " + str.getClass().getName()+"@"+Integer.toHexString(System.identityHashCode(str)));

        // 获取字符串变量的 Class
        Class<?> strClass = str.getClass();
        // 获取字符串变量对应的 Class 中的 value 字段
        Field declaredField = null;
        try {
            declaredField = strClass.getDeclaredField("value");
            // 保证获取的字段能够被访问
            declaredField.setAccessible(true);
            String newStr = "修改后的字符串变量取值";
            // 修改字符串变量的 value 字段的取值
            declaredField.set(str, declaredField.get(newStr));
            System.out.println(str + "   地址:" + System.identityHashCode(str));
            System.out.println("新:" + " 地址: " + str.getClass().getName()+"@"+Integer.toHexString(System.identityHashCode(str)));
        } catch (Exception e) {
            e.printStackTrace();
        }
输出结果:

修改前的字符串变量取值   地址:1782704802
旧: 地址: java.lang.String@6a41eaa2
修改后的字符串变量取值   地址:1782704802
新: 地址: java.lang.String@6a41eaa2

最终结果:值确实被修改了,但是引用地址没有变。但实际开发中禁止使用这种方式。还是推荐使用StringBuilder可变字符串进行操作。

举报

相关推荐

0 条评论