import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
class test
{html
public static void main(String []args) {
Integer a = 1000;java
Integer b = 2000;緩存
swap(a, b); //實現該函數,使得a,b的值交換函數
Integer c=1000;
.net
System.out.println(a + "-" + b + "-" + a.getClass()+" c:"+c); //2000-1000-class java.lang.Integer c:1000htm
/*若是a=1,b=2,c=1則輸出結果中的c會變成2,緣由參考Interger緩存(-128到127),修改了緩存裏的值致使1變成2了*/blog
}get
static void swap(Integer a, Integer b) {
int temp = a;io
try {
Class clazz = a.getClass();
Field value = clazz.getDeclaredField("value");
value.setAccessible(true);
value.setInt(a, b);
value.setInt(b, temp);
} catch (Exception ex) {
ex.printStackTrace();
}class
}
http://www.blogjava.net/sundc/archive/2013/06/08/400382.html
From:https://www.cnblogs.com/xuejianxiyang/p/9155397.html