核心思想:通过反射设置integer的value属性。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| public class Swap { public static void main(String[] args) { Integer i1 = 1; Integer i2 = 2; System.out.println("before:" + "i1:" + i1+ "- i2:" + i2) ; swap(i1,i2); System.out.println("after:" + "i1:" + i1+ "- i2:" + i2) ;
System.out.println(new Integer(1) == i1);
} public static void swap(Integer i1,Integer i2) { try { Field field = Integer.class.getDeclaredField("value"); field.setAccessible(true); int tmp = i1.intValue(); field.setInt(i1,i2); field.setInt(i2,tmp); } catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); } } }
|