Java通過反射機制使用非預設構造器建立物件
阿新 • • 發佈:2019-01-26
1、Class類方法:getConstructors()
在JDK文件中,對於該方法有如下解釋: Returns an array containingConstructor
objects reflecting
all the public constructors of the class represented by this Class
object.返回一個含有反射所有的該類的public構造器的Constructor物件的陣列。 注意,是public的構造器,其他的訪問許可權都是無法探測到的。 經過實驗,在陣列中存放的構造器物件,是按照構造器的定義順序的。
2、Constructor物件的newInstance()
public T newInstance(Object... initargs) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException如此,可使用initargs(初始化引數)來使用非預設構造器了。
3、實驗程式
// ConstructorTest.java import java.lang.reflect.*; class OtherConstructor { public OtherConstructor(float b, int i) { System.out.println("OtherConstructor(float, int): " + b + " " + i); } public OtherConstructor(String s) { System.out.println("OtherConstructor(String): " + s); } public OtherConstructor(int i) { System.out.println("OtherConstructor(int): " + i); } } public class ConstructorTest { public static void main(String[] args) { Constructor[] ctors = OtherConstructor.class.getConstructors(); for(Constructor ctor : ctors) System.out.println(ctor); try { ctors[0].newInstance(1.2F, 5); ctors[1].newInstance("Hello"); ctors[2].newInstance(45); } catch(Exception e) { throw new RuntimeException(e); } } }
執行結果如下: