问题
我想使用Class.newInstance()但我实例化的类没有一个无效的构造函数。因此,我需要能够传递构造函数参数。有没有办法做到这一点?
#1 热门回答(173 赞)
Class.getDeclaredConstructor(String.class).newInstance("HERESMYARG");
#2 热门回答(81 赞)
myObject.getClass().getDeclaredConstructors(types list).newInstance(args list);
编辑:根据评论看起来像指向类和方法名称是不够的一些用户。有关更多信息,请查看getting constuctor和invoking it的文档。
#3 热门回答(54 赞)
假设你有以下构造函数
class MyClass {
public MyClass(Long l, String s, int i) {
}
}
你将需要显示你打算使用此构造函数,如下所示:
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);