Java中的invoke使用

来源:互联网 发布:新概念3必背课文知乎 编辑:程序博客网 时间:2024/05/20 18:02

package testbao;
import java.lang.reflect.Method;
public class TestM
{

public static void main(String[] args)
{

try{

TestM t = new TestM(); //实例化类
Class c = t.getClass(); //得到这个类的方法
Class[] cargs = new Class[2]; //对应的方法参数 String[] str,Integer stri 个数
String[] realArgs = {"aa","bb","cc"}; //对应的数组
cargs[0] = realArgs.getClass(); //现象应的class中对应String[] str 数组
Integer in = new Integer(3); //对应的 Integer
cargs[1] = in.getClass(); //实现对应的class中对应的Integer stri
Method m = c.getMethod("test",cargs); //调用了test方法,返回值为Method变量
Object[] inArgs = new Object[2];
inArgs[0] = realArgs; //变量参数一
inArgs[1] = in; //变量参数二
m.invoke(t,inArgs);

}catch(Exception e){System.out.println(e);}

}
public void test2(){
 System.out.println("ok");
}

public void test(String[] str,Integer stri)
{

for(int j = 0; j < str.length; j ++)
System.out.println(str[j]);
System.out.println(stri.intValue());

}

 

}
//
invoke(Object proxy, Method method, Object[] args)
在代理实例上处理方法调用并返回结果。
//
proxy - 在其上调用方法的代理实例
method - 对应于在代理实例上调用的接口方法的 Method 实例。Method 对象的声明类将是在其中声明方法的接口,该接口可以是代理类赖以继承方法的代理接口的超接口。
args - 包含传入代理实例上方法调用的参数值的对象数组,如果接口方法不使用参数,则为 null。基本类型的参数被包装在适当基本包装器类(如 java.lang.Integer 或 java.lang.Boolean)的实例中。

原创粉丝点击