pclass = Class.forName("get_class_method.Person");//Field ageField = pclass.getField("age");//因為age成員變量是私有的,所以會產生NoSuchFieldException異常Field ageField = pclass.getDeclaredField("age");//獲得該對象反映此 Class 對象所表示的類或接口的指定已聲明字段Object obj = pclass.newInstance();//ageField.set(obj, 12);//因為age是私有的,所以即使獲取到了,還是不能訪問,如果硬要訪問,就要強制設置訪問權限 ageField.setAccessible(true);//對于構造函數和普通成員方法都可利用相應的setAccessible()函數進行設置!//雖然獲取到了該字節碼的字段,如果設置或得到該字段的具體的值,那么必須指明是哪一個對象的!ageField.set(obj, 12);//設置字段的值System.out.println(ageField.get(obj));//獲取字段的值
//普通成員函數的獲取Method method1 = pclass.getMethod("method1", null);method1.invoke(obj, null);Method method2 = pclass.getMethod("method2", String.calss, int.class);method2.invoke(obj, "小強", 20);
?