MyBatis源碼解析5-MapperProxy與JDK Proxy動態代理

JDK proxy(JDK動態代理)

包括jdk中三個重要的類

java.lang.reflect.Proxy
java.lang.reflect.InvocationHandler
sun.misc.ProxyGenerator

用的時候
Proxy.java

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

}
Proxy.newProxyInstance(classLoader, new Class[] {StudentMapper.class},
new MapperProxy()
):


public interface StudentMapper {
	List<Student> list();
}

newProxyInstance動態生成一個代理類,命名爲( $Proxy0, $Proxy1…, 假如爲 $Proxy6 )

$Proxy6 這個類實現了一個接口我們傳入的interface, 這裏我們以StudentMapper爲例.

也就是根據StudentMapper.xml的sql配置實現了StudentMapper中的所有的method的實現。

具體怎麼實現的呢?

答案:ProxyGenerator通過寫彙編程序實現的,asm

private ProxyGenerator.MethodInfo generateMethod() throws IOException {
...
var9.writeShort(ProxyGenerator.this.cp.getInterfaceMethodRef("java/lang/reflect/InvocationHandler", "invoke", "(Ljava/lang/Object;Ljava/lang/reflect/Method;[Ljava/lang/Object;)Ljava/lang/Object;"));

...
}

其中這裏是生成彙編ASM代碼。去動態創建一個Class ,$Proxy0, 後面的數字0是不斷增長的(比如0, 1,2,3,4…)

getInterfaceMethodRef("java/lang/reflect/InvocationHandler", "invoke", "(Ljava/lang/Object;Ljava/lang/reflect/Method;[Ljava/lang/Object;)Ljava/lang/Object;")

也就是每個$Proxy6中每個用戶自定義的method的實現。
都是

return invocationHandler.invoke($Proxy6, listMethod.class, null);

總結下全過程

Proxy.newProxyInstance()
產生了一個代理類 $Proxy6

public class $Proxy6 implements StudentMapper {
private InvocationHandler handler;
public $Proxy6(InvocationHandler mapperProxy) {
	handler = mapperProxy;
}
public List<Student> list() {
	return handler.invoke(this, 
	StudentMapper.class.getDeclaredMethod("list),
	null);
}

MapperProxy定義如下:

public class MapperProxy implements InvocationHandler {
	@Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
      if (Object.class.equals(method.getDeclaringClass())) {
        return method.invoke(this, args);
      } else if (isDefaultMethod(method)) {
        return invokeDefaultMethod(proxy, method, args);
      }
    } catch (Throwable t) {
      throw ExceptionUtil.unwrapThrowable(t);
    }
    final MapperMethod mapperMethod = cachedMapperMethod(method);
    return mapperMethod.execute(sqlSession, args);
  }
}

mapperMethod.execute(sqlSession, args)會去執行數據庫操作。

如何找到創建動態代理類的代碼ProxyGenerator

首先去找到java.lang.reflect.Proxy#newProxyInstance

Class<?> cl = getProxyClass0(loader, intfs);
final Constructor<?> cons = cl.getConstructor(constructorParams);
            final InvocationHandler ih = h;
            if (!Modifier.isPublic(cl.getModifiers())) {
                AccessController.doPrivileged(new PrivilegedAction<Void>() {
                    public Void run() {
                        cons.setAccessible(true);
                        return null;
                    }
                });
            }
return cons.newInstance(new Object[]{h});

可見getProxyClass0(loader, intfs)獲取或創建了一個proxyClass (意思是代理類).最後根據cl創建了一個構造方法,最後用構造方法創建了一個代理對象。
查看getProxyClass0(loader, intfs);

  private static Class<?> getProxyClass0(ClassLoader loader,
                                           Class<?>... interfaces) {
        if (interfaces.length > 65535) {
            throw new IllegalArgumentException("interface limit exceeded");
        }

        // If the proxy class defined by the given loader implementing
        // the given interfaces exists, this will simply return the cached copy;
        // otherwise, it will create the proxy class via the ProxyClassFactory
        return proxyClassCache.get(loader, interfaces);
    }

proxyClassCache

  private static final WeakCache<ClassLoader, Class<?>[], Class<?>>
        proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());

看下ProxyClassFactory的實現

/**
     * A factory function that generates, defines and returns the proxy class given
     * the ClassLoader and array of interfaces.
     */
    private static final class ProxyClassFactory
        implements BiFunction<ClassLoader, Class<?>[], Class<?>>
    {
        // prefix for all proxy class names
        private static final String proxyClassNamePrefix = "$Proxy";

        // next number to use for generation of unique proxy class names
        private static final AtomicLong nextUniqueNumber = new AtomicLong();

        @Override
        public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) {

            Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.length);
            for (Class<?> intf : interfaces) {
                /*
                 * Verify that the class loader resolves the name of this
                 * interface to the same Class object.
                 */
                Class<?> interfaceClass = null;
                try {
                    interfaceClass = Class.forName(intf.getName(), false, loader);
                } catch (ClassNotFoundException e) {
                }
                if (interfaceClass != intf) {
                    throw new IllegalArgumentException(
                        intf + " is not visible from class loader");
                }
                /*
                 * Verify that the Class object actually represents an
                 * interface.
                 */
                if (!interfaceClass.isInterface()) {
                    throw new IllegalArgumentException(
                        interfaceClass.getName() + " is not an interface");
                }
                /*
                 * Verify that this interface is not a duplicate.
                 */
                if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) {
                    throw new IllegalArgumentException(
                        "repeated interface: " + interfaceClass.getName());
                }
            }

            String proxyPkg = null;     // package to define proxy class in
            int accessFlags = Modifier.PUBLIC | Modifier.FINAL;

            /*
             * Record the package of a non-public proxy interface so that the
             * proxy class will be defined in the same package.  Verify that
             * all non-public proxy interfaces are in the same package.
             */
            for (Class<?> intf : interfaces) {
                int flags = intf.getModifiers();
                if (!Modifier.isPublic(flags)) {
                    accessFlags = Modifier.FINAL;
                    String name = intf.getName();
                    int n = name.lastIndexOf('.');
                    String pkg = ((n == -1) ? "" : name.substring(0, n + 1));
                    if (proxyPkg == null) {
                        proxyPkg = pkg;
                    } else if (!pkg.equals(proxyPkg)) {
                        throw new IllegalArgumentException(
                            "non-public interfaces from different packages");
                    }
                }
            }

            if (proxyPkg == null) {
                // if no non-public proxy interfaces, use com.sun.proxy package
                proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
            }

            /*
             * Choose a name for the proxy class to generate.
             */
            long num = nextUniqueNumber.getAndIncrement();
            String proxyName = proxyPkg + proxyClassNamePrefix + num;

            /*
             * Generate the specified proxy class.
             */
            byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
                proxyName, interfaces, accessFlags);
            try {
                return defineClass0(loader, proxyName,
                                    proxyClassFile, 0, proxyClassFile.length);
            } catch (ClassFormatError e) {
                /*
                 * A ClassFormatError here means that (barring bugs in the
                 * proxy class generation code) there was some other
                 * invalid aspect of the arguments supplied to the proxy
                 * class creation (such as virtual machine limitations
                 * exceeded).
                 */
                throw new IllegalArgumentException(e.toString());
            }
        }
    }

我們重點看其中的這幾行

long num = nextUniqueNumber.getAndIncrement();
String proxyName = proxyPkg + proxyClassNamePrefix + num;

/*
 * Generate the specified proxy class.
 */
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
    proxyName, interfaces, accessFlags);
try {
    return defineClass0(loader, proxyName,
                        proxyClassFile, 0, proxyClassFile.length);

proxyName這裏就是 xxx.yyy.$Proxy0 ,而ProxyGenerator.generateProxyClass()生成動態類的字節碼byte[].
defineClass0是一個native放啊放,這個方法根據字節碼生成真正的class。

ProxyGenerator.generateProxyClass裏面就真正構建彙編代碼ASM來生成class.
具體怎麼做的,大家看下ProxyGenerator裏的實現即可,而且上文已經有所說明,這裏不再贅述。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章