java - java反射constructor.newInstance给出“错误数量的参数”
问题描述
如何在下面修复我的代码?
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
解决方案
从以下文档:Constructor#newInstance
如果构造函数的声明类是非静态上下文中的内部类,则构造函数的第一个参数需要是封闭实例;请参阅 Java™ 语言规范的第 15.9.3 节。
因为You
是一个内部类,你需要一个它的封闭类testReflection
的实例,来创建一个You
. 为此,您可以使用以下内容:
You y = (You) constructor.newInstance(new testReflection(), "xzy");
我还建议将您的类名更改TestReflection
为遵循正确的命名约定。
推荐阅读
- python - 获取“OSError:无法运行 gpg () - 它可能不可用。” python-gnupg 出错
- reactjs - Reactjs - window.addEventListener hashchange 仅在组件最初加载时才起作用
- javascript - 在 cypress 测试中获取文本的出现次数
- java - 如何从 .jar 创建 .exe
- android-videoview - Android 视频不适用于所有密度
- excel - 以编程方式将列转置为保持第一列的行,就像在 excel 2013 中一样
- angular - Angular NGRX 效果没有任何反应
- c++ - 局部变量的右值引用和移动
- php - 如何在 PHP 中从 IP 设置速率限制?
- python - self.fp = open(self.filename, '%sb' % omode) TypeError: coercing to Unicode: need string or buffer, Field found