public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
Integer a=1,b=2;
System.out.println("before:a="+a+",b="+b);
swap(a,b);
System.out.println("after:a="+a+",b="+b);
}
private static void swap(Integer a, Integer b) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
Field field=Integer.class.getDeclaredField("value");
field.setAccessible(true);
int tmp=a.intValue();
field.set(a, b);
field.set(b, tmp);
}
以上代码在WIN10环境,JDK8下输出
--- 2018-05-28
前几天偶然想起来了Integer.cache的问题,把它带入这里,疑惑就可以解开了。因此,如果要实现交换,应该如下图所示:
一定要new 一个出来
网友评论