Java方法的值传递机制可以访问这篇博客:https://www.cnblogs.com/lixiaolun/p/4311863.html, 今天我要写的是如何利用反射来交换两个变量的值。
private static void swap(Integer x, Integer y) {
try {
Field field = Integer.class.getDeclaredField("value");
field.setAccessible(true); //private final int value; Integer中value的声明是private
//为了防止下面x的值的变化而引起temp值的变化,必须为temp开启一个新的内存空间存放值
Integer temp = new Integer(x);
field.set(x, y.intValue()); //x的值发生了改变
field.set(y, temp);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
main方法进行测试:
public static void main(String[] args) {
Integer a = 2, b = 8;
System.out.println("a=" + a + ",b=" + b);
swap(a, b);
System.out.println("a=" + a + ",b=" + b);
}
结果如下: