动态代理简述

6 篇文章 0 订阅
4 篇文章 0 订阅

动态代理

Aop 中,面向切面编程 就是基于动态代理来实现的

每一个动态代理的类都需要实现 InvocationHandler 接口
每一个代理类都管理到一个Handler. 通过代理对象调用一个方法时, 就会转发为由 InvocationHandler 接口中的 invoke 方法来调用。

 @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        return null;
    }

参数说明:

proxy : 生成的代理对象

method : 我们所要调用方法的Method对象

args : 该Mehod所需要的方法参数

Proxy 这个类提供了很多的方法 newProxyInstancegetProxyClassgetInvocationHandlergetMethods 等,我们用的最多的是 newProxyInstance 该方法返回的是一个代理对象,委托给我们传入的InvocationHandler实例。

@return a new proxy object that delegates to the handler {@code h}

方法声明:

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

参数说明:

loader:类加载器类型,由哪个类加载器来加载代理对象

interfaces :一组接口,代理对象会实现该接口。

invocationHandler:当代理对象调用方法时,会关联到Handler 并调用该 invoke 方法。

Demo

定义一个接口

public interface PeopleInterface {

    public void doSomething();

}

该接口实现

public class StudentImpl implements PeopleInterface {

    @Override
    public void doSomething() {
        System.out.println("学习");
    }
}

定义一个类实现 InvocationHandler

public class TestHandler implements InvocationHandler {


    private PeopleInterface realObj;

    public TestHandler(PeopleInterface realObj) {
        this.realObj = realObj;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("代理类: "+proxy.getClass().getName());
        System.out.println("代理方法: "+method);
        System.out.println("方法执行前");
        method.invoke(realObj,args);
        System.out.println("方法执行后");
        return null;
    }
}

proxy 为我们接口生成的代理类。

客户端代码

 @Test
    public void testProxy(){
        StudentImpl people = new StudentImpl();
        Class<?>[] interfaces = people.getClass().getInterfaces();
        System.out.println("interface length : "+interfaces.length);
        TestHandler helloProxy = new TestHandler(people);
        PeopleInterface mPeopleProxy = (PeopleInterface) Proxy.newProxyInstance(helloProxy.getClass().getClassLoader(),interfaces, helloProxy);
        mPeopleProxy.doSomething();
    }

打印:

interface length : 1
代理类: com.sun.proxy.$Proxy4
代理方法: public abstract void com.test.mike.sourcelook.PeopleInterface.doSomething()
方法执行前
学习
方法执行后

注意: newProxyInstance 创建的代理对象是在 jvm 运行时动态生成的。不是我们的PeopleInterface 类型,命名是以$开头的

com.test.mike.sourcelook.PeopleInterface.doSomething()

说明我们在使用动态创建的 代理对象调用方法时,实际上是 委托给了与其关联的 TestHandler 对象。

参考资料:
http://www.cnblogs.com/xiaoluo501395377/p/3383130.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值