Constructor objects reflecting
all the public constructors of the class represented by this Class object.public T newInstance(Object... initargs)
throws InstantiationException,
IllegalAccessException,
IllegalArgumentException,
InvocationTargetException
如此,可使用initargs(初始化参数)来使用非默认构造器了。// 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);
}
}
}
原文:http://blog.csdn.net/pdcxs007/article/details/19477103