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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 01:28:02  来源:igfitidea点击:

java.lang.IllegalArgumentException: argument type mismatch on string array

java

提问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)

parametersis a string array, and this is the declaration of my level1ClassSimilarityForUsermethod

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

invokeexpects 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 Objectarray before giving it to invokeshould 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 })改为