如何使用反射在java中调用带有变量参数的方法?

Sha*_*mik 4 java reflection

我正在尝试使用java反射调用带有变量参数的方法.这是承载方法的类:

public class TestClass {

public void setParam(N ... n){
    System.out.println("Calling set param...");
}
Run Code Online (Sandbox Code Playgroud)

这是调用代码:

try {
        Class<?> c = Class.forName("com.test.reflection.TestClass");
        Method  method = c.getMethod ("setParam", com.test.reflection.N[].class);
        method.invoke(c, new com.test.reflection.N[]{});
Run Code Online (Sandbox Code Playgroud)

我在调用invoke的最后一行以"错误的参数数量"的形式得到IllegalArgumentException.不知道我做错了什么.

任何指针将不胜感激.

  • 谢谢

gor*_*tde 14

public class Test {

public void setParam(N... n) {
    System.out.println("Calling set param...");
}

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws Exception {
    Test t=new Test();
    Class<?> c = Class.forName("test.Test");
    Method  method = c.getMethod ("setParam", N[].class);
    method.invoke(t, (Object) new N[]{});
}
}
Run Code Online (Sandbox Code Playgroud)

适合我.

  1. 将你的N []转换为对象
  2. 在实例上调用invoke,而不是在类上调用