[英]java reflection constructor.newInstance gives "wrong number of arguments"
How to fix my code below?如何修复我下面的代码?
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();
}
}
}
The exception message is:异常消息是:
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
From the documentation of Constructor#newInstance
:从Constructor#newInstance
的文档中:
If the constructor's declaring class is an inner class in a non-static context, the first argument to the constructor needs to be the enclosing instance;如果构造函数的声明类是非静态上下文中的内部类,则构造函数的第一个参数需要是封闭实例; see section 15.9.3 of The Java™ Language Specification.请参阅 Java™ 语言规范的 15.9.3 节。
Because You
is an inner class, you need an instance of its enclosing class, testReflection
, to create an instance of You
.因为You
是一个内部类,所以需要它的封闭类testReflection
的实例来创建You
的实例。 To do this, you can use the following:为此,您可以使用以下方法:
You y = (You) constructor.newInstance(new testReflection(), "xzy");
I also recommend changing your class name to TestReflection
as that follows the proper naming conventions.我还建议将您的类名更改为TestReflection
因为它遵循正确的命名约定。
The hint is on this line (the constructor takes 2 parameters):提示在这一行(构造函数采用 2 个参数):
Constructor constructor =
You.class.getConstructor(testReflection.class, String.class);
You need to send an instance of testReflection
to newInstance()
:您需要将testReflection
的实例发送到newInstance()
:
testReflection outerObject = new testReflection();
You y = (You)constructor.newInstance(outerObject, "xzy");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.