使用多个参数从 MyClass.class 创建一个实例
Creating an instance from MyClass.class with multiple parameters
我想创建 Item.class 的实例。它需要两个对象作为构造函数参数。
First FirstObject = new First();
Second SecondObject = new Second();
Class[] constructorArgs = new Class[]{First.class,Second.class};
Item.class.getConstructor(constructorArgs).newInstance(FirstObject, SecondObject);
这似乎不起作用。我收到一个编译器错误:
unhandled exception Java.Lang.NoSuchMethodException
如何修复?
NoSuchMethodException
是一个已检查的异常,因此您需要将 getConstructor()
调用包装在 try-catch
块中,或者声明此代码所在的方法 throws
this异常。
try {
Item.class.getConstructor(constructorArgs).newInstance(FirstObject, SecondObject);
} catch (NoSuchMethodException e) {
// log the error
e.printStackTrace();
}
我想创建 Item.class 的实例。它需要两个对象作为构造函数参数。
First FirstObject = new First();
Second SecondObject = new Second();
Class[] constructorArgs = new Class[]{First.class,Second.class};
Item.class.getConstructor(constructorArgs).newInstance(FirstObject, SecondObject);
这似乎不起作用。我收到一个编译器错误:
unhandled exception Java.Lang.NoSuchMethodException
如何修复?
NoSuchMethodException
是一个已检查的异常,因此您需要将 getConstructor()
调用包装在 try-catch
块中,或者声明此代码所在的方法 throws
this异常。
try {
Item.class.getConstructor(constructorArgs).newInstance(FirstObject, SecondObject);
} catch (NoSuchMethodException e) {
// log the error
e.printStackTrace();
}