import java.lang.reflect.Field;
public class Main {
public static void main(String[] args) {
Integer a = 1;
Integer b = 2;
System.out.println("before swap a=" + a + ";b=" + b);
swap(a, b);
System.out.println("after swap a=" + a + ";b=" + b);
}
private static void swap(Integer num1, Integer num2) {
// System.out.println("after swap a=" + num2 + ";b=" + num1);
// System.exit(0);
try {
Field field = Integer.class.getDeclaredField("value");
field.setAccessible(true);
int tmp = num1;
field.set(num1, num2);
//IntegarCache的缓存范围[-128,127]
field.set(num2, new Integer(tmp));
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
}
}
网友评论