MyBatisソース解析5-MapperProxyとJDK Proxyダイナミックエージェント

36899 ワード

JDK proxy(JDKダイナミックエージェント)
jdkの3つの重要なクラスを含む
java.lang.reflect.Proxy
java.lang.reflect.InvocationHandler
sun.misc.ProxyGenerator

使う時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();
}


新ProxyInstanceは、($Proxy 0、$Proxy 1...、$Proxy 6の場合)という名前のプロキシクラスを動的に生成します.
$Proxy 6というクラスはインタフェースを実現し、ここでは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,$Proxy 0を作成し、後ろの数字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;")


すなわち,各$Proxy 6におけるユーザごとにカスタマイズされたmethodの実装である.すべて
return invocationHandler.invoke($Proxy6, listMethod.class, null);

全過程を総括する.


Proxy.新ProxyInstance()は、プロキシクラス$Proxy 6を生成します.
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});

getProxyClass 0(loader,intfs)がproxyClassを取得または作成することがわかる.最後にclに基づいて構築方法を作成し、最後に構築方法でプロキシオブジェクトを作成します.getProxyClass 0(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.$Proxy 0、ProxyGenerator.generateProxyClass()動的クラスのバイトコードbyte[].defineClass 0はnative放啊放であり、この方法はバイトコードに基づいて本当のclassを生成する.
ProxyGenerator.generateProxyClassでは、アセンブリコードASMを構築してclassを生成します.具体的には、ProxyGeneratorの実装を見てください.また、上記で説明したように、ここでは説明しません.