为了账号安全,请及时绑定邮箱和手机立即绑定

我可以将Class.newInstance()与构造函数参数一起使用吗?

我可以将Class.newInstance()与构造函数参数一起使用吗?

阿波罗的战车 2019-10-16 14:59:43
我想使用,Class.newInstance()但是我要实例化的类没有空构造函数。因此,我需要能够传递构造函数参数。有没有办法做到这一点?
查看完整描述

3 回答

?
PIPIONE

TA贡献1829条经验 获得超9个赞

MyClass.class.getDeclaredConstructor(String.class).newInstance("HERESMYARG");

要么


obj.getClass().getDeclaredConstructor(String.class).newInstance("HERESMYARG");


查看完整回答
反对 回复 2019-10-16
?
茅侃侃

TA贡献1842条经验 获得超21个赞

myObject.getClass().getDeclaredConstructors(types list).newInstance(args list);

编辑:根据注释似乎指向某些用户不足的指向类和方法名称。

查看完整回答
反对 回复 2019-10-16
?
MMTTMM

TA贡献1869条经验 获得超4个赞

假设您具有以下构造函数


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);


查看完整回答
反对 回复 2019-10-16
  • 3 回答
  • 0 关注
  • 1098 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信