private static void swap(Integer a, Integer b) throws NoSuchFieldException, IllegalAccessException { //利用反射修改 Field field = Integer.class.getDeclaredField("value"); //繞過安全檢查修改final值 field.setAccessible(true); //暫存a的值 int temp = a.intValue(); 交換 field.set(a, b); field.set(b, temp) //參數須要倆個object 因此這裏會裝箱 } }
這段代碼不難理解,其實就是:java
int temp = a; a = b; b = temp
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException { Integer a = 1; Integer b = 2; System.out.println("a = " + a + ", b = " + b); swap(a, b); System.out.println("a = " + a + ", b = " + b); }
a = 1, b = 2 a = 2, b = 2
public static Integer valueOf(int i) { if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); }
field.set(a, b);
a = IntegerCache.cache[1 + -(-128)] //cache[129] b = IntegerCache.cache[2 + -(-128)] //cache[130]
cache[129] = b.intValue() // cache[129] = 2;
field.set(b, temp)
IntegerCache.cache[temp + -(-128)] // temp = 1
Integer a = 1; Integer l = 1; Integer m = 1; Integer b = 2;
field.set(a, b); field.set(b, new Integer(10)); field.set(3, new Integer(11)); field.set(5, new Integer(100));
for (int i = 0; i <= 10; i++){ if(i % 10 == 0){ System.out.println(""); } System.out.print(i + " " + Integer.valueOf(i) + " , "); }
0 0 , 1 2 , 2 10 , 3 11 , 4 4 , 5 100 , 6 6 , 7 7 , 8 8 , 9 9