现炒现买__jdk动态代理

参看文章

(cglib https://blog.csdn.net/gyshun/article/details/81000997

彻底理解JAVA动态代理

https://www.cnblogs.com/flyoung2008/p/3251148.html

(个人觉得这篇文章美中不足的就是:没有源码应用案例。

下面是我在mybatis源码中挑选出的一段代码,通过分析框架中jdk动态代理的使用方式,来理解动态代理。

就像我们的题海战略,通过大量的习题,来理解抽象的概念【对动态代理原理的理解】。

希望反复看,结合看,慢慢看,达到掌握动态代理的目的。)

看完参考文章,怎么理解下面动态代理代码

 代码来自org.apache.ibatis.logging.jdbc.ConnectionLogger

怎么理解这个newInstance代码?

 解释上面的代码

InvocationHandler handler = new ConnectionLogger(conn, statementLog, queryStack);

创建一个InvocationHandler类型的对象
ClassLoader cl = Connection.class.getClassLoader();

获取类加载器
return (Connection) Proxy.newProxyInstance(cl, new Class[]{Connection.class}, handler);

根据类加载器、接口,返回需要代理的类的classtype(这里是Connection类型);

根据反射创建Connection对象,传入handler,用构造方法反射方式创建;

使用Connection代理类,使用原理是什么?

参考下图doSomething方法。

假设connection接口中有一个doSomething方法,下面是返回的代理类的伪代码。

public final void doSomething()
{
  try {
    super.handler.invoke(this, m3, null);
    // 可以这样理解 method.invoke(this,args)
    // 也就是 XXXconnection.doSomething(args)
    return;
  } catch(Error _ex) { }
  catch(Throwable throwable) {
    throw new UndeclaredThrowableException(throwable);
  }
}

参考文章中,有利于理解动态代理的代码片段

Poxy.newProxyInstance代码关键部分

 代理对象二进制编码反编译的结果

 

原文地址:https://www.cnblogs.com/windy13/p/12679305.html