反射這個知識點很早就接觸過了,當時是在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 簡單工廠模式
新聞熱點
疑難解答