写一个交换两个整型变量值的方法(反射初探)

如何在类的外部写一个方法交换两个变量的值呢?

1 public class Util {
2     public static void swap(int x,int y){
3         int t = x;
4         x = y;
5         y = t;
6     }
7 }
1 public class Test {
2     public static void main(String[] args) {
3         int a = 1;
4         int b = 2;
5         Util.swap(a, b);
6         System.out.println("a = "+a);  //a = 1
7         System.out.println("b = "+b);  //b = 2
8     }
9 }

  因为java是值传递(通俗的说就是,我把我指向的对象传递给你,你也指向这个对象,你可以改变这个对象的内容,但我仍然指向这个对象),上面做法不行。基本数据类型和对象的引用变量存放在栈中,常量存放在常量池中,对象本身存放在堆中。

  一、基本数据类型的引用与对象的引用有所不同,例如:int x = 1,在栈中创建引用x再去常量池中找有没有常量1,若没有则将常量1放进常量池,并令x指向 1.其它基本类型以及字符串常量同理。故 Test类中,调用swap方法后,a仍然指向1,b仍然指向2.

  二、引用变量存放的是堆中对象的内存地址,对于对象引用的传递(如:Student a = new Student("张三");Student t = a),传递的是内存地址,这时 t 也指向对象 new Student("张三"),改变 t 指向对象的内容, x 所指向对象的内容也会改变。

  所以无法在外面写一个方法改变两个整型变量的值!(个人观点)

  但是,可以在外面写一个方法改变封装类Integer的值,通过 set 方法改变引用所指向对象的值。但 Ingeter 是JDK提供的,查看源码, Integer 有私有属性 value ,没有公共的 set方法。利用反射机制

 1 import java.lang.reflect.Field;
 2 
 3 public class Util {
 4     public static void swap(Integer x,Integer y){
 5         int t = x;    //不能写:Integer t = x,t和x指向同一个对象,第10行,t指向的内容会随着x改变
 6         Class xClass = x.getClass();
 7         try {
 8             Field f = xClass.getDeclaredField("value");
 9             f.setAccessible(true);
10             f.set(x, y);
11             f.set(y, t);
12         } catch (Exception e) {
13             e.printStackTrace();
14         }
15     }
16 }
1 public class Test {
2     public static void main(String[] args) {
3         Integer a = new Integer(1);
4         Integer b = new Integer(2);
5         Util.swap(a, b);
6         System.out.println("a = "+a);  //a = 2
7         System.out.println("b = "+b);  //b = 1
8     }
9 }

 

  

 

 

posted @ 2013-05-03 12:04  强混劣势路  阅读(533)  评论(0编辑  收藏  举报