1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | import java.lang.reflect.*; public class ReflectEX1 { public static void main(String[] args) { try { Class c = Class.forName("Mouse"); Constructor cstr = c.getConstructor(int.class); Object obj = cstr.newInstance(10); Method mtd = c.getMethon("show", int.class); Object robj = mtd.invoke(obj, 2); System.out.println(robj); Field fd = c.getField("age"); System.out.println(fd.getInt(obj)); } catch (NoSuchMethodException e) { System.out.println("找不到此名稱的方法"); } catch (NullPointerException e) { System.out.println("名稱為 null"); } catch (SecurityException e) { System.out.println("有安全問題"); } catch (ClassNotFoundException e) { System.out.println("找不到指定的類別"); } catch (IllegalAccessException e) { System.out.println("無法存取"); } catch (InstantiationException e) { System.out.println("無法產生實體"); } catch (InvocationTargetException e) { System.out.println("呼叫發生錯誤"); } catch (NoSuchfieldException e) { System.out.println("無法取得屬性"); } } } |
Direct link: https://paste.plurk.com/show/134386