无意中看到的一个题目,然后就试着做了下,发现用到的知识点还蛮多的
public static void main(String[] args) {
Integer a = 100 , b = 20;
System.out.println("befor : a = " + a + ", b = " + b);
swap(a, b);
System.out.println("befor : a = " + a + ", b = " + b);
}
public static void swap(Integer i1, Integer i2) {
try {
Field f = Integer.class.getDeclaredField("value");
f.setAccessible(true);
Integer tmp =new Integer(i1.intValue());
f.set(i1, i2.intValue());
f.set(i2, tmp);
} catch(Exception e) {
e.printStackTrace();
}
}
//befor : a = 100, b = 20
//befor : a = 20, b = 100
//运用的知识点:
//值的传递
//对象引用的值是内存地址
//发射的可访问性
//自动装箱
//Integer装箱的对象缓存