兩個數組不是一個意思啊。
我們應該把數組轉為objet,這樣才表示一個參數。
import java.lang.reflect.Method; public class MethodTest { public void a(String[] args) { System.out.println("a"); } public static void main(String[] args) throws Exception { MethodTest obj = new MethodTest(); Method m = obj.getClass().getMethod("a", String[].class); m.invoke(obj, new String[1]); // new String[1] 其實是null,是一個object m.invoke(obj, (Object) new String[] {}); // 這里強制轉成了object,所以也是object m.invoke(obj, new String[] {}); // 報錯,這里是個數組,是個object數組,a方法只有一個參數,所以報錯 } }
結果是
a
a
Exception in thread "main"
java.lang.IllegalArgumentException: wrong number of arguments
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)