2012-01-12 54 views
2

我想用java反射调用具有可变参数的方法。下面是它承载的方法的类:如何在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[]{}); 

我越来越抛出:IllegalArgumentException在“错误的参数数目”的形式,在最后一行在那里我调用invoke。不知道我做错了什么。

任何指针将不胜感激。

  • 感谢

回答

9
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[]{}); 
} 
} 

为我工作。

  1. 你要把你的N []为Object
  2. 调用来调用的实例,而不是对
+0

试过,没有投到'(对象)' - 我得到了和你一样的异常。因此,只需添加演员(并正确的点号1),你会没事的。 – gorootde 2012-01-12 23:52:02

+0

对,我错过了Object到Object []。万分感谢。 – Shamik 2012-01-12 23:57:23

+0

@Shamik:如果你知道你想要调用的方法,可以使用dp4j来避免这种问题 – simpatico 2012-01-13 20:21:48

3

。在你的代码片段没有TestClass实例上被调用的收作方法初探。您需要TestClass实例,而不仅仅是TestClass本身。在c上拨打newInstance(),并将此调用的结果用作method.invoke()的第一个参数。

此外,以确保您的数组被视为一个参数,而不是一个可变参数,你需要投它对象:

m.invoke(testClassInstance, (Object) new com.test.reflection.N[]{}); 
+0

我是这么认为的,并试图更早。这就是我所做的。类 c = Class.forName(“com.test.reflection.TestClass”);对象iClass = c.newInstance();方法method = c.getMethod(“setParam”,com.test.reflection.N []。class); method.invoke(iClass,new com.test.reflection.N [] {});我得到“错误数量的参数”异常。 – Shamik 2012-01-12 23:46:25

+0

查看我的编辑。我测试了它,它工作。 – 2012-01-12 23:52:52

+0

非常感谢,感谢您的帮助。 – Shamik 2012-01-12 23:58:01

相关问题