java动态代理使用过程(mybatis源码用的非常多)

背景
  • 记录动态代理的使用过程
  • 理解动态代理做了一件什么事情
过程
  • 接口
public interface InterfacePlugin {
    void test(String name);
}
  • InvocationHandler的实现类
public class Plugin implements InvocationHandler {

    private InterfacePlugin interfacePlugin = new InterfacePluginImpl();

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("调用了接口InvocationHandler的实现类Plugin");
        if (method.getName().equals("test")) {
            System.out.println("执行类Plugin的业务逻辑过程:name=" + args[0]);
        }
        Object invoke = method.invoke(interfacePlugin, "impl");
        return null;
    }
}
  • 接口的实现类
public class InterfacePluginImpl implements InterfacePlugin{

    @Override
    public void test(String name) {
        System.out.println("InterfacePluginImpl: " + name);
    }
}
  • 测试类
public class ProxyTest {
    public static void main(String[] args) {
        InterfacePlugin interfacePlugin = (InterfacePlugin)Proxy.newProxyInstance(
                ProxyTest.class.getClassLoader(),
                new Class[]{InterfacePlugin.class},
                new Plugin());

        interfacePlugin.test("life");
    }
}
  • 测试打印结果
    在这里插入图片描述
  • 其他细节
  1. 添加了一个接口的实现类。Plugin类组合了这个实现类。这一部分跟动态代理没有任何关系,反射方法调用。
小结
  • 动态代理,Java标准库提供了一种动态代理功能:可以在运行期动态创建接口interface的实例
  • 动态代理,真正的业务逻辑处理过程其实是InvocationHandler的invoke方法
  • 动态代理, jvm底层其实就是通过反射拿到接口的元信息,然后自己根据元信息生成class类,而这个class类就包含了开发者的所有业务逻辑过程
  • 动态代理,就是把接口进行了实例化,能够通过实例调用方法。底层就是生成了对应功能的一个类。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值