簡體   English   中英

如何使用反射在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[]{});
}
}

適合我。

  1. 將你的N []轉換為對象
  2. 在實例上調用invoke,而不是在類上調用

您的代碼段中沒有調用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM