我正面臨一個問題,我需要使用反射調用來調用帶有參數String,String,String ...的方法。我的代碼如下如何對一個方法執行反射調用後攜帶String,String,String ...作爲參數?
public void testArrayParams(String first, String second, String... strings) {
System.out.println("First: " + first);
System.out.println("Second: " + second);
System.out.println("Size of String... strings: " + strings.length);
for(int i = 0; i < strings.length; i ++) {
System.out.println(i + ": " + strings[i]);
}
}
及以下的主要方法
public static void main(String[] args) {
Dummy dummy = new Dummy();
//dummy.testArrayParams("Hello", "World", "This is ", "passed in ", "format String... strings.");
String[] params = {"Hello", "World", "This is ", "passed in ", "format String... strings."};
String method = "testArrayParams";
try {
Class<?> clazz = Class.forName("com.bt.testafix.utils.Dummy");
Method[] methods = clazz.getMethods();
for (Method m : methods) {
if (m.getName().equalsIgnoreCase(method)) {
//m.invoke(clazz, (Object[]) params);
m.invoke(clazz, new Object[]{params});
break;
}
}
} catch (ClassNotFoundException | IllegalArgumentException | IllegalAccessException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
它拋出異常下面當我運行的代碼
java.lang.IllegalArgumentException: object is not an instance of declaring class
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
我試圖m.invoke(clazz, (Object[]) params);
變化,這是一個鑄件,但仍然給出相同的例外。任何想法我可以解決這個問題?
將代碼從'm.invoke(clazz,new Object [] {params});'改爲'm.invoke(dummy,params);' 第一個參數守ld是你希望調用該方法的類的實例。 – Gautam