package test;
import java.lang.reflect.Method;
public class InvokeTest {
/**
*
* main 方法
* @param args
* void
*/
public static void main(String[] args) {
try {
InvokeTest invokeTest = new InvokeTest();
//1.第一步获取方法的映射
//String[] realArgs = {"",""};//定义一个与execute方法第1个参数对应的String数组(注意此数组只为获取方法的映射)
//Integer in = new Integer(0);//定义一个与execute方法第2个参数对应的Integer对象
//Class[] c_args = new Class[2];
//c_args[0] = realArgs.getClass();//分别获取以上两个参数的class
//c_args[1] = in.getClass();
//Method method = invokeTest.getClass().getMethod("execute", c_args);//返回值为test方法的映射(类型Method)
/**
* 注意,以上几句(11-16行)可以写成下面一句
* 目的是获取execute方法的映射,第一个参数是方法,第二个参数是execute方法所需要的参数列表,类型是class
* 所以当execute方法没有参数时,getMethod第二个参数为null即可
*/
Method method = invokeTest.getClass().getMethod("execute",
new Class[] { String[].class, Integer.class });
//2.第二步调用方法
//String[] a1={"zhong","cheng"};//这里的数组用于做真正调用时的参数
//Integer a2=new Integer(5);//同上
//Object[] allArgs = new Object[2];
//allArgs[0] = a1;
//allArgs[1] = a2;
//Object[] result = (Object[])method.invoke(invokeTest, allArgs);//调用execute方法并获取返回值
/**
* 注意,以上几句(21-26行)可以写成下面一句
* 目的是调用实例invokeTest的execute方法,参数(包含一个String数组和一个Integer对象)类型是Object
* invoke()方法的第一个参数表示被调用的方法所属类的实例,所以如果execute是静态方法,
* invoke的第一个参数可以为空
*/
Object[] result = (Object[])method.invoke(invokeTest, new Object[] {
new String[] { "zhong", "cheng" }, new Integer(5) });
//打印出返回值
for(int i=0;i<result.length;i++){
System.out.print(result[i]);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* 用于测试的execute方法,此处只是将String[]和Integer的值打印出来
* 并返回一个提示性的字符串数组
* @param String[] str
* @param Integer intN
* String[]
*/
public String[] execute(String[] str, Integer intN) {
for (int j = 0; j < str.length; j++) {
System.out.println(str[j]);
}
System.out.println(intN.intValue());
return new String[]{"display ","have ","bean ","finished "," !"};
}
}