zoukankan      html  css  js  c++  java
  • Java反射-修改String常量

    /*
    * ReflectString.java
    * Version 1.0.0
    * Created on 2017年12月15日
    * Copyright ReYo.Cn
    */
    package reyo.sdk.utils.test.reflect;
    
    import java.lang.reflect.Field;
    
    public class ReflectString {
    
        public static void main(String[] args) {
            String s1 = "reyo";
            String s2 = "reyo";
            String s3 = new String("reyo");
            String s4 = new String(s1);
            System.out.println("s1==s2:" + (s1 == s2));
            System.out.println("s1==s3:" + (s1 == s3));
            System.out.println("s3==s4:" + (s3 == s4));
            try {
                Field f = String.class.getDeclaredField("value");
                System.out.print("Accessible: " + f.isAccessible());
                f.setAccessible(true);
                System.out.println(" -> " + f.isAccessible());
                char[] v = (char[]) f.get(s1);// 获取S1的内部value数组
                System.out.print("
    value:");
                System.out.println(v);
                v[0] = 'x';// 修改数组
                v = new char[1];// 目测因为是get到的是引用的复制,这个引用改变不影响原引用
                v[0] = 'y';
                System.out.print("value:");
                System.out.println(v);
    
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
            System.out.println("
    s1:" + s1 + "
    s2:" + s2 + "
    s3:" + s3 + "
    s4:" + s4);
            System.out.println("
    s1==s2:" + (s1 == s2));
            System.out.println("s1==s3:" + (s1 == s3));
            System.out.println("s3==s4:" + (s3 == s4));
        }
    }

    s1==s2:true
    s1==s3:false
    s3==s4:false
    Accessible: false -> true

    value:reyo
    value:y

    s1:xeyo
    s2:xeyo
    s3:xeyo
    s4:xeyo

    s1==s2:true
    s1==s3:false
    s3==s4:false

  • 相关阅读:
    Java开发环境搭建
    MySQL优化
    js正则表达式,验证身份证
    获取urlc参数
    Oracle解锁
    Qt 常用类 (4)—— QPoint
    Qt 常用类——QStandardItemModel
    Qt QTableWidget用法总结
    Qt 随机数
    C++ static类成员,static类成员函数
  • 原文地址:https://www.cnblogs.com/interdrp/p/8044744.html
Copyright © 2011-2022 走看看