–一个含有这种方法的Java类–
public class Dao {
public void Method2(String[] params){
//do something
}
}
– 正确的方法–
public class Test {
public static void main(String[] args) throws Exception{
Class classToCall = Class.forName(“Dao”);
String[] argu ={“1″,”2″};
Method methodToExecute = classToCall.getDeclaredMethod(“Method2″, new Class[]{String[].class});
methodToExecute.invoke(classToCall.newInstance(), new Object[]{argu});
}
}
– 错误的方法,会得到异常 java.lang.IllegalArgumentException: wrong number of arguments—
public class Test {
public static void main(String[] args) throws Exception{
Class classToCall = Class.forName(“Dao”);
String[] argu ={“1″,”2″};
Method methodToExecute = classToCall.getDeclaredMethod(“Method2″, new Class[]{String[].class});
methodToExecute.invoke(classToCall.newInstance(), argu);
}
}
原因:invoke方法的第二个参数接受的是Object数组,并把数组的每一个元素作为方法的一个参数。所以如果某一个参数为数组,要在外面用new Object[]{}包起来