Class.forName("className").newInstance()
总是调用没有参数的默认构造函数。
要调用,而不是无参数无参数的构造函数参数化的构造,
- 你必须传递类型
Class[]
得到Constructor
与参数类型的Class
getDeclaredConstructor
方法你必须创建构造函数实例通过传递值Object[]
为
newInstance
方法Constructor
示例代码:
import java.lang.reflect.*;
class NewInstanceWithReflection{
public NewInstanceWithReflection(){
System.out.println("Default constructor");
}
public NewInstanceWithReflection(String a){
System.out.println("Constructor :String => "+a);
}
public static void main(String args[]) throws Exception {
NewInstanceWithReflection object = (NewInstanceWithReflection)Class.forName("NewInstanceWithReflection").newInstance();
Constructor constructor = NewInstanceWithReflection.class.getDeclaredConstructor(new Class[] {String.class});
NewInstanceWithReflection object1 = (NewInstanceWithReflection)constructor.newInstance(new Object[]{"StackOverFlow"});
}
}
输出:
java NewInstanceWithReflection
Default constructor
Constructor :String => StackOverFlow