java reflection constructor.newInstance给出;错误的参数数量“;
如何修复下面的代码java reflection constructor.newInstance给出;错误的参数数量“;,java,reflection,constructor,Java,Reflection,Constructor,如何修复下面的代码 package mypackage; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; public clas
package mypackage;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
public class testReflection {
public class You {
public You(String s) {
}
public void f(String s, int i) {
System.out.println(i + 100);
}
}
public static void main(String[] args) throws NoSuchMethodException {
Constructor constructor =
You.class.getConstructor(testReflection.class, String.class);
try {
You y = (You)constructor.newInstance("xzy");//Exception!!!!
System.out.println("ok");
y.f("xyz",2);
}catch(Exception e){
e.printStackTrace();
}
}
}
例外消息是:
java.lang.IllegalArgumentException: wrong number of arguments
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at mypackage.testReflection.main
从构造函数的#newInstance
:
testReflection outerObject = new testReflection();
You y = (You)constructor.newInstance(outerObject, "xzy");
如果构造函数的声明类是非静态上下文中的内部类,那么构造函数的第一个参数需要是封闭实例;参见Java规范第15.9.3节™ 语言规范
因为You
是一个内部类,所以需要其封闭类的实例testReflection
,来创建You
的实例。为此,您可以使用以下方法:
You y = (You) constructor.newInstance(new testReflection(), "xzy");
我还建议您将类名更改为TestReflection
,因为这遵循了正确的命名约定。提示在这一行(构造函数接受2个参数):
您需要将testReflection
的实例发送到newInstance()
:
对于您最近提出的关于如何获取内部类构造函数并使用它创建新实例的问题,已经有了答案:您在
getConstructor
调用中特别列出了testReflection.class
。
testReflection outerObject = new testReflection();
You y = (You)constructor.newInstance(outerObject, "xzy");