Java的反射

Java的反射非常強大,傳遞class, 可以動態的生成該類、取得這個類的所有信息,包括裏面的屬性、方法以及構造函數等,甚至可以取得其父類或父接口裏面的內容。

  obj.getClass().getDeclaredMethods();//取得obj類中自己定義的方法, 包括私有的方法。
  obj.getClass().getMethods();//取得obj類中自己定義的方法及繼承過來的方法, 但私有方法得不到。
  同樣, 對field也是一樣,obj.getClass().getDeclaredFields();取得的是這個類中所有的屬性,包括私有的field; 對obj.getClass().getFields();//取得是自己以及接繼承來的屬性, 但不能取得自己的私有屬性。

Java代碼  收藏代碼
  1. static Object create(Class clazz) throws Exception {  
  2.     Constructor con = clazz.getConstructor(String.class);  
  3.     Object obj = con.newInstance("test name");  
  4.     return obj;  
  5.   }  
  6.   
  7.   static void invoke1(Object obj, String methodName)  
  8.       throws IllegalArgumentException, IllegalAccessException,  
  9.       InvocationTargetException, Exception, NoSuchMethodException {  
  10.     Method[] ms = obj.getClass().getDeclaredMethods();  
  11.     ms = obj.getClass().getMethods();  
  12.     for (Method m : ms) {  
  13.       // System.out.println(m.getName());  
  14.       if (methodName.equals(m.getName()))  
  15.         m.invoke(obj, null);  
  16.     }  
  17.   
  18.     Method m = obj.getClass().getMethod(methodName, null);  
  19.     m.invoke(obj, null);  
  20.   }  
  21.   
  22.   static void field(Class clazz) throws Exception {  
  23.     Field[] fs = clazz.getDeclaredFields();  
  24.     //fs = clazz.getFields();  
  25.     for (Field f : fs)  
  26.       System.out.println(f.getName());  
  27.   }  
  28.     
  29.   static void annon(Class clazz) throws Exception {  
  30.     Annotation[] as = clazz.getAnnotations();  
  31.   }  


  1. package com.yuqiaotech.simplejee.javase.reflect;  
  2.   
  3. import java.beans.BeanInfo;  
  4. import java.beans.Introspector;  
  5. import java.beans.PropertyDescriptor;  
  6. /** 
  7.  * 使用BeanInfo來設置和讀取對象的屬性。 
  8.  */  
  9. public class BeanInfoSample {  
  10.     static class User{  
  11.         private String username;  
  12.         private String password;  
  13.         private String gender;  
  14.         public String getUsername() {  
  15.             return username;  
  16.         }  
  17.         public void setUsername(String username) {  
  18.             this.username = username;  
  19.         }  
  20.         public String getPassword() {  
  21.             return password;  
  22.         }  
  23.         public void setPassword(String password) {  
  24.             this.password = password;  
  25.         }  
  26.         public String getGender() {  
  27.             return gender;  
  28.         }  
  29.         public void setGender(String gender) {  
  30.             this.gender = gender;  
  31.         }  
  32.     }  
  33.     public static void main(String[] args) throws Exception {  
  34.         User u = new User();  
  35.         u.setUsername("Tom");  
  36.         u.setPassword("123");  
  37.         u.setGender("male");  
  38.           
  39.         BeanInfo beanInfo = Introspector.getBeanInfo(User.class);  
  40.         PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();  
  41.         for (PropertyDescriptor pd : propertyDescriptors) {  
  42.             String proName = pd.getName();  
  43.             Object v = pd.getReadMethod().invoke(u, null);  
  44.             System.out.println(proName+"="+v);  
  45.         }  
  46.     }  
  47. }  


  1. package com.yuqiaotech.simplejee.javase.reflect;  
  2.   
  3. import java.lang.reflect.*;  
  4. /** 
  5.  * 1、獲取類的相關信息 
  6.  * 2、知道類名,實例化出對象 
  7.  * 3、動態調用實例的方法 
  8.  *  
  9.  * 
  10.  */  
  11. public class ReflectSample {  
  12.     public static void main(String[] args) throws Exception {  
  13.         classInfo("com.yuqiaotech.simplejee.dao.BaseDao");  
  14.         newInstanceAndIncokeMethod();  
  15.     }  
  16.     private static void classInfo(String className) throws ClassNotFoundException{  
  17.         Class clazz = Class.forName(className);  
  18.           
  19.         System.out.println("all implemented interfaces");  
  20.         Class[] allInterfaces = clazz.getInterfaces();  
  21.         for (int i = 0; i < allInterfaces.length; i++) {  
  22.             System.out.println(i+"."+allInterfaces[i]);  
  23.         }  
  24.         System.out.println("all super classes");  
  25.         Class superClass = clazz.getSuperclass();  
  26.         int i = 0;  
  27.         while(superClass != null){  
  28.             System.out.println(++i+"."+superClass);  
  29.             superClass = superClass.getSuperclass();  
  30.         }  
  31.         System.out.println("methods");  
  32.         Method[] methods = clazz.getMethods();  
  33.         for (int j = 0; j < methods.length; j++) {  
  34.             Method m = methods[j];  
  35.             System.out.println(j+"."+m.getName());  
  36.         }  
  37.         System.out.println("getConstructors");  
  38.         int k = 0;  
  39.         Constructor[] cs = String.class.getConstructors();  
  40.         for (Constructor c : cs) {  
  41.             System.out.println(++k+"."+c);  
  42.         }  
  43.     }  
  44.     private static void newInstanceAndIncokeMethod() throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException{  
  45.         class Point{  
  46.             int x;  
  47.             int y;  
  48.             public Point(int x, int y){  
  49.                 this.x = x;  
  50.                 this.y = y;  
  51.             }  
  52.             public Point(){  
  53.             }  
  54.             public int getX() {  
  55.                 return x;  
  56.             }  
  57.             public void setX(int x) {  
  58.                 this.x = x;  
  59.             }  
  60.             public int getY() {  
  61.                 return y;  
  62.             }  
  63.             public void setY(int y) {  
  64.                 this.y = y;  
  65.             }  
  66.             public double getDistant(){  
  67.                 return getDistant(0,0);  
  68.             }  
  69.             public double getDistant(int x, int y){  
  70.                 int x1 = this.x-x;  
  71.                 int y1 = this.y - y;  
  72.                 return Math.sqrt(x1*x1 + y1*y1);  
  73.             }  
  74.             public String toString(){  
  75.                 return "x="+x+",y="+y;  
  76.             }  
  77.         }  
  78.           
  79.         System.out.println("常規方式:");  
  80.         Point ox = new Point(3,4);  
  81.         System.out.println(ox);  
  82.         System.out.println("1111result="+ox.getDistant());  
  83.         System.out.println("1111result="+ox.getDistant(5,8));  
  84.           
  85.         System.out.println("反射方式:");  
  86.         //Class clazz = Point.class;  
  87.         Class clazz = Class.forName("com.yuqiaotech.simplejee.javase.reflect.ReflectSample$1Point");  
  88.         System.out.println("獲取Point類的構造函數對象,使用該對象得到一個Point類的實例");  
  89.         //獲取代表這個構造函數的對象public Point(int x, int y)  
  90.         Constructor c = clazz.getConstructor(int.classint.class);  
  91.         Object[] args = new Object[] {34};  
  92.         //Point o = new Point(3,4);  
  93.         Object o = c.newInstance(args);  
  94.         System.out.println(o);  
  95.         System.out.println("調用上述代碼得到的實例的public double getDistant()方法,並執行它");  
  96.         //public double getDistant()  
  97.         Method m = clazz.getMethod("getDistant"null);  
  98.         //Double result = o.getDistant();  
  99.         Double result = (Double)m.invoke(o, null);  
  100.         System.out.println("result="+result);  
  101.         System.out.println("調用上述代碼得到的實例的public double getDistant(int x, int y)方法," +  
  102.                 "並執行getDistant(5,8)");  
  103.         //public double getDistant(int x, int y)  
  104.         Method m2 = clazz.getMethod("getDistant"new Class[]{int.class,int.class});  
  105.         //Double result2 = o.getDistant(5,8);  
  106.         Double result2 = (Double)m2.invoke(o, new Integer[]{5,8});  
  107.         System.out.println("result2="+result2);  
  108.     }  
  109. }  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章