java反射簡單記錄

來源:互聯網
上載者:User

1.   Java 反射API的第一個主要作用是擷取程式在運行時刻的內部結構。這對於程式的檢查工具和調試器來說,是非常實用的功能。只需要短短的十幾行代碼,就可以遍曆出來一個Java類的內部結構,包括其中的構造方法、聲明的域和定義的方法等。這不得不說是一個很強大的能力。只要有了java.lang.Class類 的對象,就可以通過其中的方法來擷取到該類中的構造方法、域和方法。對應的方法分別是getConstructor、getField和getMethod。這三個方法還有相應的getDeclaredXXX版本,區別在於getDeclaredXXX版本的方法只會擷取該類自身所聲明的元素,而不會考慮繼承下來的。Constructor、Field和Method這三個類分別表示類中的構造方法、域和方法。這些類中的方法可以擷取到所對應結構的中繼資料。

2.待測試類別

Java代碼

  1. package com.home.action.test.mode.reflection;   
  2.   
  3. import java.util.Map;   
  4.   
  5. public class Counter {   
  6.     public int count ;   
  7.     public Map<String, Object> map;   
  8.        
  9.     public Counter(int count) {   
  10.         this.count = count;   
  11.     }   
  12.        
  13.     public void increase(int step) {   
  14.         count = count + step;   
  15.         System.out.println("count: "+count);   
  16.     }   
  17. }  
package com.home.action.test.mode.reflection;import java.util.Map;public class Counter {    public int count ;    public Map<String, Object> map;        public Counter(int count) {        this.count = count;    }        public void increase(int step) {        count = count + step;        System.out.println("count: "+count);    }}

3.測試方法

Java代碼

  1. package com.home.action.test.mode.reflection;   
  2.   
  3. import java.lang.reflect.Constructor;   
  4. import java.lang.reflect.Field;   
  5. import java.lang.reflect.InvocationTargetException;   
  6. import java.lang.reflect.Method;   
  7. import java.lang.reflect.ParameterizedType;   
  8. import java.lang.reflect.Type;   
  9.   
  10. /**  
  11.  * 測試基本類的反射  
  12.  * @author li  
  13.  */  
  14. public class Test {   
  15.     @SuppressWarnings("rawtypes")   
  16.     public static void main(String[] args) {   
  17.         try {   
  18.             //建構函式   
  19.             Constructor<Counter> contructor = Counter.class.getConstructor(int.class);   
  20.             System.out.println("contructorName: "+contructor.getName());   
  21.                
  22.             Counter counter = contructor.newInstance(10);   
  23.             counter.increase(10);   
  24.                
  25.             //基本方法   
  26.             Method[] methods = Counter.class.getMethods();   
  27.             for(Method method: methods) {   
  28.                 System.out.println("method: "+method.getName());   
  29.             }   
  30.                
  31.             Method method = Counter.class.getMethod("increase", int.class);   
  32.             method.invoke(counter, 6);   
  33.                
  34.             //屬性值   
  35.             Field[] fields = Counter.class.getFields();   
  36.             for(Field field: fields) {   
  37.                 System.out.println("fieldName: "+field.getName());   
  38.             }   
  39.                
  40.             //count類型要設定public 否則擷取不到, 提示異常資訊   
  41.             Field field = Counter.class.getField("count");   
  42.             System.out.println("countField: "+field.getName());   
  43.                
  44.             //處理泛型   
  45.             Field mapField = Counter.class.getDeclaredField("map");   
  46.             Type type = mapField.getGenericType();   
  47.             System.out.println("mapType: "+ type.toString());   
  48.                
  49.             if(type instanceof ParameterizedType) {   
  50.                 ParameterizedType paramerizedType = (ParameterizedType)type;   
  51.                    
  52.                 Type[] actualTypes = paramerizedType.getActualTypeArguments();   
  53.                 for(Type t: actualTypes) {   
  54.                     if(t instanceof Class){   
  55.                         Class clz = (Class)t;   
  56.                         System.out.println("classType: "+ clz.getName());   
  57.                     }   
  58.                 }   
  59.             }   
  60.         } catch (SecurityException e) {   
  61.             e.printStackTrace();   
  62.         } catch (NoSuchMethodException e) {   
  63.             e.printStackTrace();   
  64.         } catch (IllegalArgumentException e) {   
  65.             e.printStackTrace();   
  66.         } catch (InstantiationException e) {   
  67.             e.printStackTrace();   
  68.         } catch (IllegalAccessException e) {   
  69.             e.printStackTrace();   
  70.         } catch (InvocationTargetException e) {   
  71.             e.printStackTrace();   
  72.         } catch (NoSuchFieldException e) {   
  73.             e.printStackTrace();   
  74.         }   
  75.     }   
  76. }  

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.