我在类中有一个方法如下
class Sample{
public void doSomething(String ... values) {
//do something
}
public void doSomething(Integer value) {
}
}
//other methods
.
.
.
Run Code Online (Sandbox Code Playgroud)
现在我得到IllegalArgumentException:下面的参数数量错误
Sample object = new Sample();
Method m = object.getClass().getMethod( "doSomething", String[].class );
String[] arr = {"v1","v2"};
m.invoke( object, arr ) // exception here
Run Code Online (Sandbox Code Playgroud)
invoke 期望一组参数.
在您的情况下,您有一个类型为array的参数,因此您应该发送一个大小为1的数组,其中包含1个成员,这是第一个(也是唯一的)参数.
像这样:
Sample object = new Sample();
Method m = object.getClass().getMethod( "doSomething", String[].class );
String[] arr = {"v1","v2"};
Object[] methodArgs = new Object[] {arr};
m.invoke( object, methodArgs ); // no exception here
Run Code Online (Sandbox Code Playgroud)
将您的String数组包装成一个Object数组:
Sample object = new Sample();
Method m = object.getClass().getMethod("doSomething", String[].class);
String[] arr = {"v1", "v2"};
m.invoke(object, new Object[] {arr});
Run Code Online (Sandbox Code Playgroud)