public class Ccc {
public static void main(String[] args) throws Exception {
String a = "111";
String b = "222";
// swap1(a, b);//No, a = 222, b = 222
swap1(a, b);//Yes, a = 222, b = 111
System.out.println(a);
System.out.println(b);
}
private static void swap1(String a, String b) throws Exception {
String newA = b;//newA -> b = "222"
String newB = a;//newB -> a = "111" , newB指向a的地址值
Field fieldA = a.getClass().getDeclaredField("value");
fieldA.setAccessible(true);
fieldA.set(a, newA.toCharArray());//a = newA = "222" 导致 newB -> = "222"
Field fieldB = b.getClass().getDeclaredField("value");
fieldB.setAccessible(true);
fieldB.set(b, newB.toCharArray());//newB = "222"
}
private static void swap2(String a, String b) throws Exception {
String newA = new String(b);//newA = "222"
String newB = new String(a);//newB = "111",newB没有指向a的地址值,而是新开辟空间将a的值复制进去存储
Field fieldA = a.getClass().getDeclaredField("value");
fieldA.setAccessible(true);
fieldA.set(a, newA.toCharArray());//newA = "222"
Field fieldB = b.getClass().getDeclaredField("value");
fieldB.setAccessible(true);
fieldB.set(b, newB.toCharArray());//newB = "111"
}
}