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

我想使用,Class.newInstance()但是我要实例化的类没有空构造函数。因此,我需要能够传递构造函数参数。有没有办法做到这一点?



阿波罗的战车
浏览 1104回答 3
3回答

PIPIONE

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

茅侃侃

myObject.getClass().getDeclaredConstructors(types list).newInstance(args list);编辑:根据注释似乎指向某些用户不足的指向类和方法名称。

MMTTMM

假设您具有以下构造函数class MyClass {    public MyClass(Long l, String s, int i) {    }}您将需要证明打算使用该构造函数,如下所示:Class classToLoad = MyClass.class;Class[] cArg = new Class[3]; //Our constructor has 3 argumentscArg[0] = Long.class; //First argument is of *object* type LongcArg[1] = String.class; //Second argument is of *object* type StringcArg[2] = int.class; //Third argument is of *primitive* type intLong l = new Long(88);String s = "text";int i = 5;classToLoad.getDeclaredConstructor(cArg).newInstance(l, s, i);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java