Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.lang.reflect.Field;
- /**
- * @description: 利用反射在方法中交换两个 Integer 的值
- * @author: 枫子翰
- * @date: 2017/12/5 19:52
- * @version: V1.0
- */
- public class TestChange {
- public static void main(String[] args)throws Exception {
- Integer x = 100;
- Integer y = 8;
- System.out.println("交换前:x="+x+";y="+y);
- changeRight(x,y);
- //changeWrong1(x,y);
- //changeWrong2(x,y);
- System.out.println("交换后:x="+x+";y="+y);
- Integer p = 100;
- System.out.println("Integer p = 100; p="+p);
- }
- public static void changeRight(Integer i1,Integer i2) throws Exception {
- Field fun=Integer.class.getDeclaredField("value");
- fun.setAccessible(true);
- Integer swap=new Integer(i1.intValue());
- fun.set(i1,i2);
- fun.set(i2,swap);
- }
- public static void changeWrong1(Integer i1,Integer i2) throws Exception{
- Field fun = Integer.class.getDeclaredField("value");
- fun.setAccessible(true);
- Integer swap = i1;
- fun.set(i1,i2);
- fun.set(i2,swap);
- }
- private static void changeWrong2(Integer x, Integer y) throws Exception{
- Field fun = Integer.class.getDeclaredField("value");
- fun.setAccessible(true);
- int swap = x;
- fun.set(x,y);
- fun.set(y,swap);
- }
- }
Add Comment
Please, Sign In to add comment