传入多个参数时候invoke方法的使用

    科技2022-07-10  282

    Method类的invoke(Object obj,Object args[])方法接收的参数必须为对象。在学习jdk的动态代理时,invoke方法里面需要传入参数数组。以下代码来此狂神说的例子狂神说Spring06:静态/动态代理模式

    public class ProxyInvocationHandler implements InvocationHandler { private Object target; public void setTarget(Object target) { this.target = target; } //生成代理类 public Object getProxy(){ return Proxy.newProxyInstance(this.getClass().getClassLoader(), target.getClass().getInterfaces(),this); } // proxy : 代理类 // method : 代理类的调用处理程序的方法对象. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { log(method.getName()); Object result = method.invoke(target, args); return result; } public void log(String methodName){ System.out.println("执行了"+methodName+"方法"); } }

    首先生成代理类:Proxy的newProxyInstance()方法,有三个参数:

    loader: 用哪个类加载器去加载代理对象

    interfaces:动态代理类需要实现的接口

    h:动态代理方法在执行时,会调用h里面的invoke方法去执行

    public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) throws IllegalArgumentException

    然后代理类调用真实角色的方法,并返回对象。invoke()方法也有三个参数:

    proxy:就是代理对象,newProxyInstance方法的返回对象

    method:调用的方法

    args: 方法中的参数

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { log(method.getName()); Object result = method.invoke(target, args); return result; }

    这里用到invoke就是反射的invoke方法,第一个参数就是对象实例,一般也是由反射获取,第二个是参数列表,必须为对象。

    invoke(obj, new Object[]{“args1”, “args2”})

    反射之invoke方法 一个例子弄懂invoke方法

    Processed: 0.009, SQL: 8