Guest User

Untitled

a guest
Jan 22nd, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. import java.lang.reflect.Field;
  2.  
  3. /**
  4. * @description: 利用反射在方法中交换两个 Integer 的值
  5. * @author: 枫子翰
  6. * @date: 2017/12/5 19:52
  7. * @version: V1.0
  8. */
  9. public class TestChange {
  10.  
  11. public static void main(String[] args)throws Exception {
  12. Integer x = 100;
  13. Integer y = 8;
  14. System.out.println("交换前:x="+x+";y="+y);
  15. changeRight(x,y);
  16. //changeWrong1(x,y);
  17. //changeWrong2(x,y);
  18. System.out.println("交换后:x="+x+";y="+y);
  19. Integer p = 100;
  20. System.out.println("Integer p = 100; p="+p);
  21. }
  22.  
  23.  
  24. public static void changeRight(Integer i1,Integer i2) throws Exception {
  25. Field fun=Integer.class.getDeclaredField("value");
  26. fun.setAccessible(true);
  27. Integer swap=new Integer(i1.intValue());
  28. fun.set(i1,i2);
  29. fun.set(i2,swap);
  30. }
  31.  
  32. public static void changeWrong1(Integer i1,Integer i2) throws Exception{
  33. Field fun = Integer.class.getDeclaredField("value");
  34. fun.setAccessible(true);
  35. Integer swap = i1;
  36. fun.set(i1,i2);
  37. fun.set(i2,swap);
  38. }
  39.  
  40. private static void changeWrong2(Integer x, Integer y) throws Exception{
  41. Field fun = Integer.class.getDeclaredField("value");
  42. fun.setAccessible(true);
  43. int swap = x;
  44. fun.set(x,y);
  45. fun.set(y,swap);
  46. }
  47.  
  48. }
Add Comment
Please, Sign In to add comment