233 java constructor
我想使用,Class.newInstance()但我实例化的类没有一个无效的构造函数.因此,我需要能够传递构造函数参数.有没有办法做到这一点?
jsi*_*ght 197
MyClass.class.getDeclaredConstructor(String.class).newInstance("HERESMYARG");
Run Code Online (Sandbox Code Playgroud)
Mar*_*rko 87
myObject.getClass().getDeclaredConstructors(types list).newInstance(args list);
Run Code Online (Sandbox Code Playgroud)
编辑:根据评论看起来像指向类和方法名称是不够的一些用户.有关更多信息,请查看获取constuctor并调用它的文档.
Mar*_*cny 68
假设您有以下构造函数
class MyClass {
public MyClass(Long l, String s, int i) {
}
}
Run Code Online (Sandbox Code Playgroud)
您将需要显示您打算使用此构造函数,如下所示:
Class classToLoad = MyClass.class;
Class[] cArg = new Class[3]; //Our constructor has 3 arguments
cArg[0] = Long.class; //First argument is of *object* type Long
cArg[1] = String.class; //Second argument is of *object* type String
cArg[2] = int.class; //Third argument is of *primitive* type int
Long l = new Long(88);
String s = "text";
int i = 5;
classToLoad.getDeclaredConstructor(cArg).newInstance(l, s, i);
Run Code Online (Sandbox Code Playgroud)
Chr*_*ung 18
不要用Class.newInstance(); 看到这个帖子:为什么Class.newInstance()是邪恶的?
像其他答案一样,请Constructor.newInstance()改用.
按照以下步骤调用参数化的consturctor.
Constructor通过Class[]
为for getDeclaredConstructor方法传递类型来获取参数类型 ClassObject[]for 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"});
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
java NewInstanceWithReflection
Default constructor
Constructor :String => StackOverFlow
Run Code Online (Sandbox Code Playgroud)