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

如何使用反射在java中使用变量参数调用方法?,java,reflection,Java,Reflection,我试图使用java反射调用一个具有可变参数的方法。下面是承载该方法的类: public class TestClass { public void setParam(N ... n){ System.out.println("Calling set param..."); } 以下是调用代码: try { Class<?> c = Class.forName("com.test.reflection.TestClass"); Method

我试图使用java反射调用一个具有可变参数的方法。下面是承载该方法的类:

public class TestClass {

public void setParam(N ... n){
    System.out.println("Calling set param...");
}
以下是调用代码:

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[]{});
试试看{
Class c=Class.forName(“com.test.reflection.TestClass”);
Method=c.getMethod(“setParam”,com.test.reflection.N[].class);
调用(c,new com.test.reflection.N[]{});
在调用invoke的最后一行,我得到了IllegalArgumentException,形式为“错误数量的参数”。不确定我做错了什么

任何指点都将不胜感激

  • 谢谢

在调用methd的代码段中没有
TestClass
实例。您需要
TestClass
的实例,而不仅仅是
TestClass
本身。在
c
上调用
newInstance()
,并将此调用的结果用作
方法.invoke()
的第一个参数

此外,为了确保数组被视为一个参数,而不是varargs,您需要将其强制转换为对象:

m.invoke(testClassInstance, (Object) new com.test.reflection.N[]{});
公共类测试{
公共无效设置参数(N…N){
System.out.println(“调用集参数…”);
}
/**
*@param指定命令行参数
*/
公共静态void main(字符串[]args)引发异常{
测试t=新测试();
c类=Class.forName(“test.test”);
方法方法=c.getMethod(“setParam”,N[].class);
调用(t,(对象)newn[]{});
}
}
对我有用

  • 将N[]强制转换为对象
  • 在实例上调用,而不是在类上调用

  • 我是这么想的,并在前面尝试过。下面是我所做的。Class c=Class.forName(“com.test.reflection.TestClass”);Object iClass=c.newInstance();Method=c.getMethod(“setParam”,com.test.reflection.N[].Class);Method.invoke(iClass,new com.test.reflection.N[]{});我得到了“错误数量的参数”异常。在没有对
    (Object)
    进行强制转换的情况下尝试了该操作-我得到了与您相同的异常。因此,只要添加强制转换(以及正确的第1点),您就可以了。没错,我错过了对Object[]的强制转换。非常感谢。@Shamik:如果您知道要调用的方法,您可以使用dp4j避免此类问题
    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[]{});
    }
    }