利用Java反射机制调用含数组参数的方法

来源:互联网 发布:怎样学好高中语文知乎 编辑:程序博客网 时间:2024/05/18 15:06

http://yourmitra.wordpress.com/2008/09/26/using-java-reflection-to-invoke-a-method-with-array-parameters/

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

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


0 0
原创粉丝点击