转载:https://www.cnblogs.com/leskang/p/6110631.html
As we all know, 在Java中, String类对象是不可变的。那么到底什么是不可变的对象呢? 可以这样认为:如果一个对象,在它创建完成之后,不能再改变它的状态,那么这个对象就是不可变的。不能改变状态的意思是,不能改变对象内的成员变量,包括基本数据类型的值不能改变,引用类型的变量不能指向其他的对象(final修饰),引用类型指向的对象的状态也不能改变。
对于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
从上文可知String的成员变量value是private final 的,也就是初始化之后不可改变。那么在这几个成员中, value比较特殊,因为他是一个引用变量,而不是真正的对象。value是final修饰的,也就是说final不能再指向其他数组对象,那么我能改变value指向的数组吗? 比如将数组中的某个位置上的字符变为下划线“_”。 至少在我们自己写的普通代码中不能够做到,因为我们根本不能够访问到这个value引用(private修饰),更不能通过这个引用去修改数组。 那么用什么方式可以访问私有成员呢? 没错,用反射, 可以反射出String对象中的value属性, 进而改变通过获得的value引用改变数组的结构。下面是实例代码:
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
原文:https://www.cnblogs.com/parrot/p/11512162.html