最近在學習MyBatis源碼時,想要查看下JDK是如何自動生成的Mapper代理類。於是仔細看了源碼,在這裏做個記錄。
package com.br.itwzhangzx02.learn;
import learn.User;
import learn.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.InputStream;
public class GeneratorClassFileTest {
public static void main(String[] args) {
//將生成的代理類class文件保存在磁盤
System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
String resource = "resources/mybatis-config.xml";
SqlSessionFactory sqlSessionFactory;
try (InputStream inputStream = Resources.getResourceAsStream(resource)) {
//1、創建SqlSessionFactory
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2、獲取sqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = getUser(sqlSession);
System.out.println(user);
}catch (Exception e){
}
}
private static User getUser(SqlSession sqlSession) {
//3、獲取mapper,斷點在這兒,然後進入
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
userMapper.toString();
//4、執行數據庫操作,並處理結果集
return userMapper.selectUser("10");
}
}
//MapperProxyFactory 類中的方法 第三個入參mapperProxy就是實現了InvocationHandler接口的類的對象
protected T newInstance(MapperProxy<T> mapperProxy) {
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
//這個是MapperRegistry類中的方法,將mapperProxyFactory 在初始化解析xml時緩存到內存中。
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
if (mapperProxyFactory == null) {
throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
}
try {//這兒,用對應的工廠負責new一個代理類的對象
return mapperProxyFactory.newInstance(sqlSession);
} catch (Exception e) {
throw new BindingException("Error getting mapper instance. Cause: " + e, e);
}
}
然後直接查看我們JDK的Proxy.newProxyInstance方法
@CallerSensitive
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
{
Objects.requireNonNull(h);
final Class<?>[] intfs = interfaces.clone();
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
}
/* 第一步:
* Look up or generate the designated proxy class.
* 這裏使用到緩存技術,從緩存中取代理類,或者直接生成一個代理類
*/
Class<?> cl = getProxyClass0(loader, intfs);
/*
* Invoke its constructor with the designated invocation handler.
*/
try {
if (sm != null) {
checkNewProxyPermission(Reflection.getCallerClass(), cl);
}
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});
} catch (IllegalAccessException|InstantiationException e) {
throw new InternalError(e.toString(), e);
} catch (InvocationTargetException e) {
Throwable t = e.getCause();
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
} else {
throw new InternalError(t.toString(), t);
}
} catch (NoSuchMethodException e) {
throw new InternalError(e.toString(), e);
}
}
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 這個對象是什麼?下面給proxyClassCache的賦值操作方法,
//final和static修飾的變量 ,所以在加載Proxy類的時候給proxyClassCache 賦值
private static final WeakCache<ClassLoader, Class<?>[], Class<?>>
proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
//WeakCache類的構造方法
//keyFactory是用來生產key的,ProxyClassFactory是用來生產代理類對象的,它倆都是實現了
//BiFunction接口的Proxy的內部類
public WeakCache(BiFunction<K, P, ?> subKeyFactory,
BiFunction<K, P, V> valueFactory) {
this.subKeyFactory = Objects.requireNonNull(subKeyFactory);
this.valueFactory = Objects.requireNonNull(valueFactory);
}
//需要到WeakCache類中,找get方法
下面是WeakCache類的get方法
public V get(K key, P parameter) {
Objects.requireNonNull(parameter);
expungeStaleEntries();
//對 key進行處理,將 null轉換爲一個 Object對象
Object cacheKey = CacheKey.valueOf(key, refQueue);
// lazily install the 2nd level valuesMap for the particular cacheKey
//延遲初始化,二級MAP
ConcurrentMap<Object, Supplier<V>> valuesMap = map.get(cacheKey);
if (valuesMap == null) {
ConcurrentMap<Object, Supplier<V>> oldValuesMap
= map.putIfAbsent(cacheKey,
valuesMap = new ConcurrentHashMap<>());
if (oldValuesMap != null) {
valuesMap = oldValuesMap;
}
}
// create subKey and retrieve the possible Supplier<V> stored by that
// subKey from valuesMap
//subKey的生成,需要查看Proxy中的KeyFactory內部類的apply方法,代碼在下面
Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
//從我們的二級map中根據key,取出來的值可能是
//代理類的工廠Factory 或緩存CacheValue
Supplier<V> supplier = valuesMap.get(subKey);
Factory factory = null;
while (true) {
if (supplier != null) {//緩存中有supplier
// supplier might be a Factory or a CacheValue<V> instance
V value = supplier.get();
//這兒取值可能情況有倆種,如果是Factory,則是生成代理類,可能失敗
//如果是CacheValue中,取值,可能爲null
if (value != null) {//supplier的get返回值不爲空
return value;
}
}
// else no supplier in cache
// or a supplier that returned null (could be a cleared CacheValue
// or a Factory that wasn't successful in installing the CacheValue)
// lazily construct a Factory
if (factory == null) {
factory = new Factory(key, parameter, subKey, valuesMap);
}
if (supplier == null) {
supplier = valuesMap.putIfAbsent(subKey, factory);
if (supplier == null) {
// successfully installed Factory
supplier = factory;
}
// else retry with winning supplier
} else {
if (valuesMap.replace(subKey, supplier, factory)) {
// successfully replaced
// cleared CacheEntry / unsuccessful Factory
// with our Factory
supplier = factory;
} else {
// retry with current supplier
supplier = valuesMap.get(subKey);
}
}
}
}
//下面的代碼是CacheKey中的
private static final Object NULL_KEY = new Object();
//對key進行包裝,爲NULL則返回一個Object對象
static <K> Object valueOf(K key, ReferenceQueue<K> refQueue) {
return key == null
// null key means we can't weakly reference it,
// so we use a NULL_KEY singleton as cache key
? NULL_KEY
// non-null key requires wrapping with a WeakReference
: new CacheKey<>(key, refQueue);
}
//WeakCache類中的map的定義,是一個二級MAP結構,同時用的是併發容器MAP
//簡單理解,外層Map的key就是類加載器運算後生成的,裏層的二級map的key就是類加載器和接口數組經
//過運算生成的,subMap中的value就是我們的代理類的一個持有者,factory或者cacheValue
// the key type is Object for supporting null key
private final ConcurrentMap<Object, ConcurrentMap<Object, Supplier<V>>> map
= new ConcurrentHashMap<>();
//KeyFactory的定義,負責生成我們的subKey
private static final class KeyFactory
implements BiFunction<ClassLoader, Class<?>[], Object>
{
@Override
public Object apply(ClassLoader classLoader, Class<?>[] interfaces) {
switch (interfaces.length) {
case 1: return new Key1(interfaces[0]); // the most frequent
case 2: return new Key2(interfaces[0], interfaces[1]);
case 0: return key0;
default: return new KeyX(interfaces);
}
}
}
上面分析:
V value = supplier.get();
這一步,我們只分析如果這個supplier是一個Factory時,也就是第一次執行UserMapper userMapper = sqlSession.getMapper(UserMapper.class);時如何生成代理類的對象(不是代理類的實例,是代表這個代理類的對象,具體可以查看java反射中Class)。第1次之後再調用時,我們的代理類對象從緩存ValueCache中拿,然後代理類對象拿到構造器對象,然後創建一個代理類的實例出來。(這個實例是,每次調用生成一個新的)
更簡單的理解:生成的代理類Class只生成一次,然後緩存起來,之後每次調用getMapper時,新生成這個代理類的實例對象。
//Factory中的get方法
@Override
public synchronized V get() { // serialize access
// re-check
Supplier<V> supplier = valuesMap.get(subKey);
if (supplier != this) {
// something changed while we were waiting:
// might be that we were replaced by a CacheValue
// or were removed because of failure ->
// return null to signal WeakCache.get() to retry
// the loop
//這一句判斷很關鍵,比如我們的下單邏輯,只能執行一次,執行完之後狀態修改,
//別的線程,拿到鎖之後,先查看狀態,是否符合預期,如果狀態不符合,
//就不執行後續操作了。
//或者一些要求冪等性的方法
return null;
}
// else still us (supplier == this)
// create new value
V value = null;
try {//創建我們的代理類對象
value = Objects.requireNonNull(valueFactory.apply(key, parameter));
} finally {
if (value == null) { // remove us on failure
valuesMap.remove(subKey, this);
}
}
// the only path to reach here is with non-null value
assert value != null;
//下面的邏輯,就是將我們的代理類對象緩存起來,將之前的subMap中的value值由factory
//替換爲我們的cacheValue ,
//之後我們的獲取代理類對象操作就不需要重新生成了,可以直接從緩存CacheValue 中get()
// wrap value with CacheValue (WeakReference)
CacheValue<V> cacheValue = new CacheValue<>(value);
// try replacing us with CacheValue (this should always succeed)
if (valuesMap.replace(subKey, this, cacheValue)) {
// put also in reverseMap
reverseMap.put(cacheValue, Boolean.TRUE);
} else {
throw new AssertionError("Should not reach here");
}
// successfully replaced us with new CacheValue -> return the value
// wrapped by it
return value;
}
}
下面分析:factory生成代理類對象。前面說過這個factory是一個ProxyClassFactory類型。所以我們查看ProxyClassFactory裏的apply方法。
value = Objects.requireNonNull(valueFactory.apply(key, parameter));
@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.
*關鍵代碼,生成代理類的class文件,返回的是char數組
*/
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());
}
}
}
private static final boolean saveGeneratedFiles = (Boolean)AccessController.doPrivileged(new GetBooleanAction("sun.misc.ProxyGenerator.saveGeneratedFiles"));
public static byte[] generateProxyClass(final String var0, Class<?>[] var1, int var2) {
ProxyGenerator var3 = new ProxyGenerator(var0, var1, var2);
final byte[] var4 = var3.generateClassFile();
if (saveGeneratedFiles) {//這個標識就是,控制是否將代理類class文件保存到磁盤
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
try {
int var1 = var0.lastIndexOf(46);
Path var2;
if (var1 > 0) {
Path var3 = Paths.get(var0.substring(0, var1).replace('.', File.separatorChar));
Files.createDirectories(var3);
var2 = var3.resolve(var0.substring(var1 + 1, var0.length()) + ".class");
} else {
var2 = Paths.get(var0 + ".class");
}
Files.write(var2, var4, new OpenOption[0]);
return null;
} catch (IOException var4x) {
throw new InternalError("I/O exception saving generated file: " + var4x);
}
}
});
}
return var4;
}
看代碼知道,有個開關可以控制生成的代理類Class文件保存到磁盤中。
上面是我保存到本地的代理類的Class文件,下面是代碼(反編譯後的)
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.sun.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;
import learn.User;
import learn.UserMapper;
public final class $Proxy0 extends Proxy implements UserMapper {
private static Method m1;
private static Method m2;
private static Method m3;
private static Method m0;
public $Proxy0(InvocationHandler var1) throws {
super(var1);
}
public final boolean equals(Object var1) throws {
try {
return (Boolean)super.h.invoke(this, m1, new Object[]{var1});
} catch (RuntimeException | Error var3) {
throw var3;
} catch (Throwable var4) {
throw new UndeclaredThrowableException(var4);
}
}
public final String toString() throws {
try {
return (String)super.h.invoke(this, m2, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
public final User selectUser(String var1) throws {
try {
return (User)super.h.invoke(this, m3, new Object[]{var1});
} catch (RuntimeException | Error var3) {
throw var3;
} catch (Throwable var4) {
throw new UndeclaredThrowableException(var4);
}
}
public final int hashCode() throws {
try {
return (Integer)super.h.invoke(this, m0, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
static {
try {
m1 = Class.forName("java.lang.Object").getMethod("equals", Class.forName("java.lang.Object"));
m2 = Class.forName("java.lang.Object").getMethod("toString");
m3 = Class.forName("learn.UserMapper").getMethod("selectUser", Class.forName("java.lang.String"));
m0 = Class.forName("java.lang.Object").getMethod("hashCode");
} catch (NoSuchMethodException var2) {
throw new NoSuchMethodError(var2.getMessage());
} catch (ClassNotFoundException var3) {
throw new NoClassDefFoundError(var3.getMessage());
}
}
}
總結:
1.我們多次調用
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
實際上使用的同一個代理類,只有第一次是通過factory生成的,之後是從緩存ValueCache中取值。
2.我們生成的代理類是繼承了Proxy類的,所以JDK動態代理不支持繼承方式,只支持接口方式。
3.我們的InvocationHandler接口的實現類的對象h,作爲構造函數的入參,傳給我們的代理類。
4.我們代理類的代理方法是委託給h的invoke方法的。