JDK动态代理

    @Test
    public void testProxy(){
        //创建InvocationHandler对象
        MyInvocationHandler handler = new MyInvocationHandler(new ProxyServiceImpl());
        //调用JDK的代理方法
        ProxyService newProxyInstance = (ProxyService)Proxy.newProxyInstance(
                proxyServiceImpl.getClass().getClassLoader(),
                proxyServiceImpl.getClass().getInterfaces(), handler);
                newProxyInstance.add();
    }

 

 

分析:JDK动态代理需要执行

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

其中参数含义:

loader – the class loader to define the proxy class(用于定义代理类的类加载器)
interfaces – the list of interfaces for the proxy class to implement(代理类要实现的接口列表)
h – the invocation handler to dispatch method invocations to(将方法调用分派到的调用处理程序,即自己定义的handler处理对象)

handler如下:(需要实现InvocationHandler接口),在重写的invoke方法中添加代理方法执行前后的逻辑处理。
public class MyInvocationHandler implements InvocationHandler {

    //被代理的对象
    private ProxyService proxyService;

    public MyInvocationHandler(ProxyService proxyService) {
        this.proxyService = proxyService;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("add()执行前。。。。");
        //真正执行的方法
        Object invoke = method.invoke(proxyService, args);
        System.out.println("add()执行后。。。。");
        return invoke;
    }
}

 

 

 

posted @ 2022-06-15 16:35  Cactus丶  阅读(57)  评论(0编辑  收藏  举报