Java反射經典執行個體

來源:互聯網
上載者:User

Java提供了一套機制來動態執行方法和構造方法,以及數組操作等,這套機制就叫——反射。反射機制是如今很多流行架構的實現基礎,其中包括Spring、Hibernate等。原理性的問題不是本文的重點,接下來讓我們在執行個體中學習這套精彩的機制。

1. 得到某個對象的屬性

 

源碼列印?
  1. public Object getProperty(Object owner, String fieldName) throws Exception {  
  2.      Class ownerClass = owner.getClass();  
  3.    
  4.      Field field = ownerClass.getField(fieldName);  
  5.    
  6.      Object property = field.get(owner);  
  7.    
  8.      return property;  
  9.  }  

Class ownerClass = owner.getClass():得到該對象的Class。

Field field = ownerClass.getField(fieldName):通過Class得到類聲明的屬性。

Object property = field.get(owner):通過對象得到該屬性的執行個體,如果這個屬性是非公有的,這裡會報IllegalAccessException。

 

2. 得到某個類的靜態屬性

 

源碼列印?
  1. public Object getStaticProperty(String className, String fieldName)  
  2.              throws Exception {  
  3.      Class ownerClass = Class.forName(className);  
  4.    
  5.      Field field = ownerClass.getField(fieldName);  
  6.    
  7.      Object property = field.get(ownerClass);  
  8.    
  9.      return property;  
  10. }  

Class ownerClass = Class.forName(className) :首先得到這個類的Class。

Field field = ownerClass.getField(fieldName):和上面一樣,通過Class得到類聲明的屬性。

Object property = field.get(ownerClass) :這裡和上面有些不同,因為該屬性是靜態,所以直接從類的Class裡取。

3. 執行某對象的方法

 

源碼列印?
  1. public Object invokeMethod(Object owner, String methodName, Object[] args) throws Exception {  
  2.    
  3.      Class ownerClass = owner.getClass();  
  4.    
  5.      Class[] argsClass = new Class[args.length];  
  6.    
  7.      for (int i = 0, j = args.length; i < j; i++) {  
  8.          argsClass[i] = args[i].getClass();  
  9.      }  
  10.    
  11.      Method method = ownerClass.getMethod(methodName, argsClass);  
  12.    
  13.      return method.invoke(owner, args);  
  14. }  

Class owner_class = owner.getClass() :首先還是必須得到這個對象的Class。

5~9行:配置參數的Class數組,作為尋找Method的條件。

Method method = ownerClass.getMethod(methodName, argsClass):通過Method名和參數的Class數組得到要執行的Method。

method.invoke(owner, args):執行該Method,invoke方法的參數是執行這個方法的對象,和參數數組。傳回值是Object,也既是該方法的傳回值。

4. 執行某個類的靜態方法

 

源碼列印?
  1. public Object invokeStaticMethod(String className, String methodName,  
  2.              Object[] args) throws Exception {  
  3.      Class ownerClass = Class.forName(className);  
  4.    
  5.      Class[] argsClass = new Class[args.length];  
  6.    
  7.      for (int i = 0, j = args.length; i < j; i++) {  
  8.          argsClass[i] = args[i].getClass();  
  9.      }  
  10.    
  11.      Method method = ownerClass.getMethod(methodName, argsClass);  
  12.    
  13.      return method.invoke(null, args);  
  14. }  

基本的原理和執行個體3相同,不同點是最後一行,invoke的一個參數是null,因為這是靜態方法,不需要藉助執行個體運行。

 

5. 建立執行個體

 

源碼列印?
  1. public Object newInstance(String className, Object[] args) throws Exception {  
  2.      Class newoneClass = Class.forName(className);  
  3.    
  4.      Class[] argsClass = new Class[args.length];  
  5.    
  6.      for (int i = 0, j = args.length; i < j; i++) {  
  7.          argsClass[i] = args[i].getClass();  
  8.      }  
  9.    
  10.      Constructor cons = newoneClass.getConstructor(argsClass);  
  11.    
  12.      return cons.newInstance(args);  
  13.    
  14. }  

這裡說的方法是執行帶參數的建構函式來建立執行個體的方法。如果不需要參數,可以直接使用newoneClass.newInstance()來實現。

Class newoneClass = Class.forName(className):第一步,得到要構造的執行個體的Class。

第5~第9行:得到參數的Class數組。

Constructor cons = newoneClass.getConstructor(argsClass):得到構造子。

cons.newInstance(args):建立執行個體。

6. 判斷是否為某個類的執行個體

 

源碼列印?
  1. public boolean isInstance(Object obj, Class cls) {  
  2.      return cls.isInstance(obj);  
  3.  }  

7. 得到數組中的某個元素

 

源碼列印?
  1. public Object getByArray(Object array, int index) {  
  2.      return Array.get(array,index);   
  3. }  

附完整源碼:

 

源碼列印?
  1. import java.lang.reflect.Array;  
  2. import java.lang.reflect.Constructor;  
  3. import java.lang.reflect.Field;  
  4. import java.lang.reflect.Method;  
  5.   
  6. /** 
  7. * Java Reflection Cookbook 
  8. * @author Michael Lee 
  9. * @since 2006-8-23 
  10. * @version 0.1a 
  11. */  
  12. public class Reflection {  
  13.     /** 
  14.      * 得到某個對象的公用屬性 
  15.      * 
  16.      * @param owner, fieldName 
  17.      * @return 該屬性對象 
  18.      * @throws Exception 
  19.      * 
  20.      */  
  21.     public Object getProperty(Object owner, String fieldName) throws Exception {  
  22.         Class ownerClass = owner.getClass();  
  23.         Field field = ownerClass.getField(fieldName);  
  24.         Object property = field.get(owner);  
  25.         return property;  
  26.     }  
  27.     /** 
  28.      * 得到某類的靜態公用屬性 
  29.      * 
  30.      * @param className   類名 
  31.      * @param fieldName   屬性名稱 
  32.      * @return 該屬性對象 
  33.      * @throws Exception 
  34.      */  
  35.     public Object getStaticProperty(String className, String fieldName)  
  36.             throws Exception {  
  37.         Class ownerClass = Class.forName(className);  
  38.         Field field = ownerClass.getField(fieldName);  
  39.         Object property = field.get(ownerClass);  
  40.         return property;  
  41.     }  
  42.   
  43.     /** 
  44.      * 執行某對象方法 
  45.      * 
  46.      * @param owner 
  47.      *            對象 
  48.      * @param methodName 
  49.      *            方法名 
  50.      * @param args 
  51.      *            參數 
  52.      * @return 方法傳回值 
  53.      * @throws Exception 
  54.      */  
  55.     public Object invokeMethod(Object owner, String methodName, Object[] args)  
  56.             throws Exception {  
  57.         Class ownerClass = owner.getClass();  
  58.         Class[] argsClass = new Class[args.length];  
  59.         for (int i = 0, j = args.length; i < j; i++) {  
  60.             argsClass[i] = args[i].getClass();  
  61.         }  
  62.         Method method = ownerClass.getMethod(methodName, argsClass);  
  63.         return method.invoke(owner, args);  
  64.     }  
  65.   
  66.       /** 
  67.      * 執行某類的靜態方法 
  68.      * 
  69.      * @param className 
  70.      *            類名 
  71.      * @param methodName 
  72.      *            方法名 
  73.      * @param args 
  74.      *            參數數組 
  75.      * @return 執行方法返回的結果 
  76.      * @throws Exception 
  77.      */  
  78.     public Object invokeStaticMethod(String className, String methodName,  
  79.             Object[] args) throws Exception {  
  80.         Class ownerClass = Class.forName(className);  
  81.         Class[] argsClass = new Class[args.length];  
  82.         for (int i = 0, j = args.length; i < j; i++) {  
  83.             argsClass[i] = args[i].getClass();  
  84.         }  
  85.         Method method = ownerClass.getMethod(methodName, argsClass);  
  86.         return method.invoke(null, args);  
  87.     }  
  88.     /** 
  89.      * 建立執行個體 
  90.      * 
  91.      * @param className 
  92.      *            類名 
  93.      * @param args 
  94.      *            建構函式的參數 
  95.      * @return 建立的執行個體 
  96.      * @throws Exception 
  97.      */  
  98.     public Object newInstance(String className, Object[] args) throws Exception {  
  99.         Class newoneClass = Class.forName(className);  
  100.         Class[] argsClass = new Class[args.length];  
  101.         for (int i = 0, j = args.length; i < j; i++) {  
  102.             argsClass[i] = args[i].getClass();  
  103.         }  
  104.         Constructor cons = newoneClass.getConstructor(argsClass);  
  105.         return cons.newInstance(args);  
  106.     }  
  107.   
  108.       
  109.     /** 
  110.      * 是不是某個類的執行個體 
  111.      * @param obj 執行個體 
  112.      * @param cls 類 
  113.      * @return 如果 obj 是此類的執行個體,則返回 true 
  114.      */  
  115.     public boolean isInstance(Object obj, Class cls) {  
  116.         return cls.isInstance(obj);  
  117.     }  
  118.       
  119.     /** 
  120.      * 得到數組中的某個元素 
  121.      * @param array 數組 
  122.      * @param index 索引 
  123.      * @return 返回指定數組對象中索引組件的值 
  124.      */  
  125.     public Object getByArray(Object array, int index) {  
  126.         return Array.get(array,index);  
  127.     }  
  128. }  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.