标签:访问权限 必须 内存结构 war src 初始化 www. declare eal
众所周知, 在Java中, String类是不可变的。那么到底什么是不可变的对象呢? 可以这样认为:如果一个对象,在它创建完成之后,不能再改变它的状态,那么这个对象就是不可变的。不能改变状态的意思是,不能改变对象内的成员变量,包括基本数据类型的值不能改变,引用类型的变量不能指向其他的对象,引用类型指向的对象的状态也不能改变。
对于Java初学者, 对于String是不可变对象总是存有疑惑。看下面代码:
String s = "ABCabc";
System.out.println("s = " + s);
s = "123456";
System.out.println("s = " + s);
打印结果为: s = ABCabc

public final class String
implements java.io.Serializable, Comparable<string>, CharSequence{
/** The value is used for character storage. */
private final char value[];
/** The offset is the first index of the storage that is used. */
private final int offset;
/** The count is the number of characters in the String. */
private final int count;
/** Cache the hash code for the string */
private int hash; // Default to 0</string>
public final class String
implements java.io.Serializable, Comparable<string>, CharSequence {
/** The value is used for character storage. */
private final char value[];
/** Cache the hash code for the string */
private int hash; // Default to 0</string>

String a = "ABCabc";
System.out.println("a = " + a);
a = a.replace(‘A‘, ‘a‘);
System.out.println("a = " + a);
打印结果为: a = ABCabc

String ss = "123456";
System.out.println("ss = " + ss);
ss.replace(‘1‘, ‘0‘);
System.out.println("ss = " + ss);
打印结果: ss = 123456
public static void testReflection() throws Exception {
//创建字符串"Hello World", 并赋给引用s
String s = "Hello World";
System.out.println("s = " + s); //Hello World
//获取String类中的value字段
Field valueFieldOfString = String.class.getDeclaredField("value");
//改变value属性的访问权限
valueFieldOfString.setAccessible(true);
//获取s对象上的value属性的值
char[] value = (char[]) valueFieldOfString.get(s);
//改变value所引用的数组中的第5个字符
value[5] = ‘_‘;
System.out.println("s = " + s); //Hello_World
}
打印结果为: s = Hello World
标签:访问权限 必须 内存结构 war src 初始化 www. declare eal
原文地址:https://www.cnblogs.com/jdbn/p/9846473.html