把下面a,b值互换,使打印结果为a=2,b=1.
import java.lang.reflect.Field;
/**
* Created by 70416 on 2018/4/7.
*/
public class App {
public static void swap(Integer i1,Integer i2) throws NoSuchFieldException, IllegalAccessException {
.....
}
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
Integer a=1,b=2;
System.out.println("开始a="+a+",b="+b);
swap(a,b);
System.out.println("结束a="+a+",b="+b);
}
}
Field field = Integer.class.getDeclaredField("value");
field.setAccessible(true);
int tmp = i1.intValue();
field.set(i1,i2.intValue());
field.set(i2,tmp);
import java.lang.reflect.Field;
/**
* Created by 70416 on 2018/4/7.
*/
public class App {
public static void swap(Integer i1,Integer i2) throws NoSuchFieldException, IllegalAccessException {
Field field = Integer.class.getDeclaredField("value");
field.setAccessible(true);
Integer tmp = new Integer(i1.intValue());
// int tmp = i1.intValue(); //Integer -127----128里的值这个就不行,指针指向了缓存里的值。
field.set(i1,i2.intValue());
field.set(i2,tmp);
}
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
Integer a=1,b=2;
// System.out.println(a==b); //Integer -127----128里的相同值,答案为true,超出缓存为false。
System.out.println("开始a="+a+",b="+b);
swap(a,b);
System.out.println("结束a="+a+",b="+b);
}
}