[Java基础]反射获取构造方法并使用
生活随笔
收集整理的這篇文章主要介紹了
[Java基础]反射获取构造方法并使用
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
代碼如下:
package ClassObjectPack;import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException;public class ReflectDemo01 {public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {Class<?> c = Class.forName("ClassObjectPack.Student");//只能拿公共構造函數(shù)Constructor<?>[] cons = c.getConstructors();for (Constructor con:cons){System.out.println(con);}System.out.println("-------------------------------------------");//拿所有的構造函數(shù)Constructor<?>[] cons01 = c.getDeclaredConstructors();for (Constructor con:cons01){System.out.println(con);}//Constructor<T> getConstructor(類<?>... parameterTypes)//返回一個 Constructor對象,該對象反映 Constructor對象表示的類的指定的公共 類函數(shù)。//Constructor<T> getDeclaredConstructor(類<?>... parameterTypes)//返回一個 Constructor對象,該對象反映 Constructor對象表示的類或接口的指定 類函數(shù)。//參數(shù):你要獲取的構造方法的參數(shù)的個數(shù)和數(shù)據(jù)類型對應的字節(jié)碼文件對象Constructor<?> con02 = c.getConstructor();// Constructor提供了一個類的單個構造函數(shù)的信息和訪問。// T newInstance(Object... initargs)// 使用此 Constructor對象表示的構造函數(shù),使用指定的初始化參數(shù)來創(chuàng)建和初始化構造函數(shù)的聲明類的新實例。Object obj = con02.newInstance();System.out.println(obj);// Student s = new Student(); // System.out.println(s);} }測試結果:
總結
以上是生活随笔為你收集整理的[Java基础]反射获取构造方法并使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [Java基础]获取Class类的对象
- 下一篇: 下半身一直瘦不下去,怎么能瘦腿