国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

反射

2019-11-06 06:02:06
字體:
來源:轉載
供稿:網友

反射這個知識點很早就接觸過了,當時是在pio做導入導出的時候,其實當時不知道那一堆代碼是什么用,還伴隨著很多的try catch,后在再知識庫里面看到了反射的知識點,才知道有這個東西,嗨呀年少無知的我喲。這幾天想著復習復習基礎知識,一開始往本本上記錄,記的記的就覺得寫字的時候碰到寫代碼好煩,好想用鍵盤,那好,我就去寫博客好了。 1.實例化class對象

Class myClass1 = null; try { myClass1 = Class.forName("com.gejiayu.learn.list.MyClass"); } catch (ClassNotFoundException e) { e.PRintStackTrace(); } Class myClass2 = new MyClass().getClass(); Class myClass3 = MyClass.class;

2.獲取父類/接口

Class superClass = myClass1.getSuperclass(); Class inter[] = myClass1.getInterfaces();

3.實例化對象

MyClass myObj1; try { myObj1 = (MyClass)myClass1.newInstance(); myObj1.setAge(1); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalaccessException e) { e.printStackTrace(); }

4.獲取構造方法

Constructor constructors[] = myClass1.getConstructors(); for(Constructor constructor:constructors){ Class types[] = constructor.getParameterTypes();//數據類型 }

5.獲取屬性

Field fields[] = myClass1.getDeclaredFields(); for(Field field:fields){ int modifier = field.getModifiers();//權限修飾符 Class type = field.getType();//數據類型 }

6.獲取方法

Method methods[] = myClass1.getMethods(); for(Method method:methods){ Class type = method.getReturnType();//返回值類型 Class types[] = method.getParameterTypes();//參數類型 Class ExceptionTypes[] = method.getExceptionTypes();//異常類型 }

7.屬性調用

try { field.setAccessible(true); field.set(myObj1, 3); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); }

8.方法調用

try { if("sayHello".equals(method.getName())){ method.invoke(myObj1); }else if("setAge".equals(method.getName())){ method.invoke(myObj1, 2); } } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); }

9.method.setAccessible(true) setAccessible是啟用和禁用訪問安全檢查的開關,并不是為true就能訪問為false就不能訪問。反射類中的Field,Method和Constructor繼承自AccessibleObject,一般情況下,我們并不能對類的私有字段進行操作,要序列化的時候,我們又必須有能力去處理這些字段,這時候,我們就需要調用AccessibleObject上的setAccessible()方法來允許這種訪問。 參考:http://blog.csdn.net/clypm/article/details/42737473

10.應用 poi操作Excel 簡單工廠模式


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 平泉县| 建湖县| 三河市| 雅江县| 尚义县| 卓尼县| 佛学| 阿合奇县| 武功县| 康马县| 分宜县| 泰和县| 商河县| 扶风县| 香港 | 疏附县| 咸阳市| 库伦旗| 黄骅市| 西充县| 乡宁县| 莱芜市| 北碚区| 江津市| 镶黄旗| 汾阳市| 株洲市| 云龙县| 灵宝市| 普陀区| 双峰县| 勃利县| 丁青县| 微山县| 广州市| 新巴尔虎右旗| 化隆| 德化县| 保靖县| 璧山县| 呼伦贝尔市|