![](/img/trans.png)
[英]Unable to invoke the method with variable arguments using reflection in java
[英]How to invoke method with variable arguments in java using 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 method = c.getMethod ("setParam", com.test.reflection.N[].class);
method.invoke(c, new com.test.reflection.N[]{});
我在調用invoke的最后一行以“錯誤的參數數量”的形式得到IllegalArgumentException。 不知道我做錯了什么。
任何指針將不勝感激。
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[]{});
}
}
適合我。
您的代碼段中沒有調用methd的TestClass
實例。 您需要TestClass
一個實例 ,而不僅僅是TestClass
本身。 在c
上調用newInstance()
,並使用此調用的結果作為method.invoke()
的第一個參數。
此外,為了確保您的數組被視為一個參數,而不是varargs,您需要將其強制轉換為Object:
m.invoke(testClassInstance, (Object) new com.test.reflection.N[]{});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.