天天看點

java中反射機制通過位元組碼檔案對象擷取字段和函數的方法

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);

本文轉自 小眼兒 部落格園部落格,原文連結:http://www.cnblogs.com/hujunzheng/p/4055928.html,如需轉載請自行聯系原作者