IllegalArgumentException:Java Constructor.newInstance() 中的参数数量错误
考虑下面的代码,
public class StartUp {
public StartUp(String[] test){}
public static void main(String[] args) throws Exception{
Constructor cd = StartUp.class.getConstructor(String[].class);
System.out.println(cd.newInstance(new String[]{}).toString());
}
}
它有什么问题?我收到以下异常:
线程“main”中出现异常 java.lang.IllegalArgumentException:参数数量错误 在 sun.reflect.NativeConstructorAccessorImpl.newInstance0(本机方法) 在 sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39) 在 sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) 在 java.lang.reflect.Constructor.newInstance(Constructor.java:513) 在 com.test.StartUp.main(StartUp.java:10)
Consider the following code,
public class StartUp {
public StartUp(String[] test){}
public static void main(String[] args) throws Exception{
Constructor cd = StartUp.class.getConstructor(String[].class);
System.out.println(cd.newInstance(new String[]{}).toString());
}
}
What's wrong with it? I get the following Exception:
Exception in thread "main" java.lang.IllegalArgumentException: wrong number of arguments
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.test.StartUp.main(StartUp.java:10)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的
String[]
正在隐式转换为Object[]
并作为空参数数组,而不是作为空数组的单个参数。试试这个:或者
甚至避免编译器必须为您创建数组:
基本上,这是可变参数处理和数组协方差的混合:(
Your
String[]
is being implicitly converted toObject[]
and taken as an empty array of arguments, instead of as a single argument which is an empty array. Try this:or
or even avoid the compiler having to create the array for you at all:
Basically this is a mixture of varargs handling and array covariance :(
您可以使用 dp4j 详细选项来回答您的问题,并获得您需要的正确反射代码:
You could use dp4j verbose option to answer your question, and get the correct reflection code that you need: