[英]Java Reflections error: Wrong number of arguments
So I'm trying to invoke a classes constructor at runtime. 所以我试图在运行时调用类构造函数。 I have the following code snippet: 我有以下代码片段:
String[] argArray = {...};
...
Class<?> tempClass = Class.forName(...);
Constructor c = tempClass.getConstructor(String[].class);
c.newInstance(argArray);
...
Whenever I compile the code and pass it a class, I get an IllegalArgumentException: wrong number of arguments. 每当我编译代码并将其传递给类时,我都会收到IllegalArgumentException:错误的参数数量。 The constructor of the class I'm calling takes in a String[] as the only argument. 我正在调用的类的构造函数将String []作为唯一参数。 What's also weird is that if I change the constructor to take in an integer and use Integer.TYPE and call c.newInstance(4) or something, it works. 还很奇怪的是,如果我将构造函数更改为采用整数并使用Integer.TYPE并调用c.newInstance(4)或其他名称,则它会起作用。 Can someone explain to me what I'm doing wrong? 有人可以向我解释我在做什么错吗? Thank you. 谢谢。
Edit;; 编辑;; Complete error: 完成错误:
java.lang.IllegalArgumentException: wrong number of arguments
[Ljava.lang.String;@2be3d80c
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
This is happening because newInstance(Object...)
takes varargs of Object
, in other words Object[]
. 发生这种情况是因为newInstance(Object...)
接受了Object
变量 ,换句话说就是Object[]
。 Since arrays are covariant, a String[]
is also an Object[]
, and argArray
is being interpretted as all arguments instead of first argument . 由于数组是协变的,因此String[]
也是Object[]
,并且argArray
被解释为所有参数,而不是第一个参数 。
jdb's solution works because it prevents the compiler from misunderstanding. jdb的解决方案之所以有效,是因为它防止了编译器的误解。 You could also write: 您还可以编写:
c.newInstance(new Object[] {argArray});
我不确定这是否是最佳解决方案,但这应该可行:
c.newInstance((Object)argArray);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.