java.lang.IllegalArgumentException:字符串数组上的参数类型不匹配
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36447647/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java.lang.IllegalArgumentException: argument type mismatch on string array
提问by Ania David
This is my code to invoke a method dynamically:
这是我动态调用方法的代码:
String[] parameters = new String[requiredParameters.length];
//here i put some values in the parameters array
method = TestRecommendations.class.getMethod("level1ClassSimilarityForUser",
String[].class);
System.out.println(":" + parameters[0] + ":");
results = (ResultSet) method.invoke(new TestRecommendations(), parameters)
parameters
is a string array, and this is the declaration of my level1ClassSimilarityForUser
method
parameters
是一个字符串数组,这是我的level1ClassSimilarityForUser
方法的声明
public ResultSet level1ClassSimilarityForUser(String[] userURI) {
I am getting this error:
我收到此错误:
java.lang.IllegalArgumentException: argument type mismatch
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
回答by Vampire
invoke
expects an Object[]
as second argument (varargs is just a convenience syntax).
I think in your case the String[]
is not taken as the first vararg argument, but the complete vararg Object[]
and thus your single strings are used as arguments which does not match String[]
.
In your case, explicitly wrapping your parameters in an Object
array before giving it to invoke
should work.
So do results = (ResultSet) method.invoke(new TestRecommendations(), new Ojbect[] { parameters })
instead
invoke
需要Object[]
作为第二个参数(varargs 只是一种方便的语法)。我认为在您的情况下, theString[]
不是作为第一个 vararg 参数,而是完整的 vararg Object[]
,因此您的单个字符串用作不匹配的参数String[]
。
在您的情况下,在将参数Object
提供给它之前将参数显式包装在数组中invoke
应该可以工作。
所以results = (ResultSet) method.invoke(new TestRecommendations(), new Ojbect[] { parameters })
改为