个人博客:小景哥哥
两个Integer的引用传递给一个swap方法在方法内部进行交换,返回后,两个引用的值是否发生变化
注:Integer在-128~127之间,有缓存
自动装箱与拆箱
反射,通过反射去修改private final的变量
import java.lang.reflect.Field;
public class Swap {
public static void main(String[] args) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
Integer a = 1, b = 2;
System.out.println("before:" + a + "," + b);
swap(a,b);
System.out.println("after:" + a + "," + b);
}
public static void swap(Integer i1, Integer i2) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException{
Field field = Integer.class.getDeclaredField("value");
field.setAccessible(true);
Integer tmp = new Integer(i1.intValue());
field.set(i1, i2.intValue());
field.set(i2, tmp);
}
}