利用java反射机制调用一个本身含有数组参数的方法需要一点点技巧。下面的代码展示了怎么样正确地和错误地使用java反射机制调用这样的方法。



–一个含有这种方法的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[]{}包起来

Object   java . lang . reflect . Method .invoke( Object  obj,  Object ... args) throws  IllegalAccessException ,  IllegalArgumentException ,  InvocationTargetException



利用java反射机制调用一个本身含有数组参数的方法需要一点点技巧。下面的代码展示了怎么样正确地和错误地使用java反射机制调用这样的方法。



–一个含有这种方法的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[]{}包起来

Object   java . lang . reflect . Method .invoke( Object  obj,  Object ... args) throws  IllegalAccessException ,  IllegalArgumentException ,  InvocationTargetException