2012-01-12 99 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

相關問題