JDK 動態(tài)代理
基本用法
public class JDKProxy implements InvocationHandler {
private ISomeInterface someInterface;
private JDKProxy(ISomeInterface someInterface) {
this.someInterface = someInterface;
}
public ISomeInterface getProxy() {
return (ISomeInterface) Proxy.newProxyInstance(this.getClass().getClassLoader(), someInterface.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
before();
Object obj = someInterface.doSomething();
after();
return obj;
}
private void after() {}
private void before() {}
}
interface ISomeInterface {
Object doSomething();
}
Proxy 和 InvocationHandler
動態(tài)代理明面上就這兩個關(guān)鍵類
InvocationHandler 里面就一個invoke方法乒验,專門用于代理類的回調(diào)漓帚。
Proxy.newProxyInstance 用于生成的代理類是掰,重點分析下內(nèi)部的復(fù)雜實現(xiàn)惹挟。
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);
}
}
三個參數(shù):
ClassLoader loader:用哪個類加載器來加載滔岳;
interfaces:都需要代理哪些接口的方法身隐;
InvocationHandler :回調(diào)的類
第一步:生成代理類
第二步:實例化代理類對象
getProxyClass0
getProxyClass0用于生成代理類
/**
* Generate a proxy class. Must call the checkProxyAccess method
* to perform permission checks before calling this.
*/
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
// 如果當(dāng)前類加載器和接口已經(jīng)被緩存邀泉,就直接返回其徙,否則就用ProxyClassFactory創(chuàng)建代理類
return proxyClassCache.get(loader, interfaces);
}
第一個if判斷接口數(shù)量胚迫,這里的65535是受java字節(jié)碼文件結(jié)構(gòu)中對接口數(shù)量的限制,u2的大小唾那。具體另行查閱java字節(jié)碼文件的構(gòu)成访锻。
private static final WeakCache<ClassLoader, Class<?>[], Class<?>> proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
proxyClassCache 是一個弱引用的緩存
proxyClassCache.get(loader, interfaces)
/**
* Look-up the value through the cache. This always evaluates the
* {@code subKeyFactory} function and optionally evaluates
* {@code valueFactory} function if there is no entry in the cache for given
* pair of (key, subKey) or the entry has already been cleared.
*
* @param key possibly null key 類加載器
* @param parameter parameter used together with key to create sub-key and
* value (should not be null) 接口對象列表
* @return the cached value (never null)
* @throws NullPointerException if {@code parameter} passed in or
* {@code sub-key} calculated by
* {@code subKeyFactory} or {@code value}
* calculated by {@code valueFactory} is null.
*/
public V get(K key, P parameter) {
Objects.requireNonNull(parameter);
expungeStaleEntries();
//1.
Object cacheKey = CacheKey.valueOf(key, refQueue);
//2.
// lazily install the 2nd level valuesMap for the particular cacheKey
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;
}
}
//3.
// create subKey and retrieve the possible Supplier<V> stored by that
// subKey from valuesMap
Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
Supplier<V> supplier = valuesMap.get(subKey);
Factory factory = null;
//4.
while (true) {
if (supplier != null) {
// supplier might be a Factory or a CacheValue<V> instance
V value = supplier.get();
if (value != null) {
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);
}
}
}
}
整個方法就是圍繞著代理類緩存來做處理。
第一部分:先將類加載器構(gòu)建成一個CacheKey的弱引用對象
private static final class CacheKey<K> extends WeakReference<K> {
// a replacement for null keys
private static final Object NULL_KEY = new 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);
}
第二部分:構(gòu)造了一個valuesMap,用于緩存類加載器對象和代理類期犬。
第三部分:subKeyFactory.apply方法通過KeyFactory和接口的數(shù)量河哑,返回了某一種Key對象,Key也是一個弱引用龟虎。
/**
* A function that maps an array of interfaces to an optimal key where
* Class objects representing interfaces are weakly referenced.
*/
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);
}
}
}
第四部分:while(true) 循環(huán)就是返回緩存的代理類璃谨,或者創(chuàng)建新的代理類。
第一圈遣总,先構(gòu)建一個Factory睬罗,作為生成代理類的工廠,并且作為value緩存到了valuesMap中旭斥,并賦值給supplier容达。
第二圈,調(diào)用Factory的get方法垂券。
// lazily construct a Factory
if (factory == null) {
factory = new Factory(key, parameter, subKey, valuesMap);
}
接下來就仔細分析一下Factory的實現(xiàn)花盐。
/**
* A factory {@link Supplier} that implements the lazy synchronized
* construction of the value and installment of it into the cache.
*/
private final class Factory implements Supplier<V> {
private final K key; // 類加載器
private final P parameter; // 接口對象列表
private final Object subKey; //接口對象構(gòu)造的Key
private final ConcurrentMap<Object, Supplier<V>> valuesMap; // <類加載,代理類生成工廠> map
Factory(K key, P parameter, Object subKey,
ConcurrentMap<Object, Supplier<V>> valuesMap) {
this.key = key;
this.parameter = parameter;
this.subKey = subKey;
this.valuesMap = valuesMap;
}
@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
//正常情況下菇爪,在外部的while(true) 循環(huán)中算芯,已經(jīng)賦值supplier = factory, 如果這里不相等,就直接返回凳宙,外部循環(huán)再執(zhí)行一次
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;
// wrap value with CacheValue (WeakReference)
CacheValue<V> cacheValue = new CacheValue<>(value);
// put into reverseMap
reverseMap.put(cacheValue, Boolean.TRUE);
// try replacing us with CacheValue (this should always succeed)
if (!valuesMap.replace(subKey, this, cacheValue)) {
throw new AssertionError("Should not reach here");
}
// successfully replaced us with new CacheValue -> return the value
// wrapped by it
return value;
}
}
主要實現(xiàn)是先生成代理類對象熙揍,并將其封裝成CacheValue,保存到valuesMap中氏涩。
關(guān)鍵部分就是生成代理類
// 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);
}
}
具體的生成過程是下面的一大段:整體過程比較簡單届囚,注釋都寫在代碼中。最后返回生成的代理類對象是尖。
回到上面的方法意系,代理類對象生成后,封裝成CacheValue饺汹,同樣是弱引用蛔添,保存到了valuesMap中。
至此兜辞,valuesMap中緩存了:接口對象列表 -> 代理類對象迎瞧;
全局map緩存了:類加載器 -> Map<接口對象列表 -> 代理類對象>
/**
* 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 如:jdk代理生成的類 == 原包名.$Proxy0
private static final String proxyClassNamePrefix = "$Proxy";
// next number to use for generation of unique proxy class names 記錄當(dāng)前生成到幾了
private static final AtomicLong nextUniqueNumber = new AtomicLong();
@Override
public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) {
//將所有的接口對象都存到map中,并且不能有重復(fù)
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();
//如果接口是非public的弦疮,就必須在同一個包下夹攒,非public跨包無法被引用到
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");
}
}
}
// 如果當(dāng)前接口沒有包名,就用com.sun.proxy胁塞。而且一定是public的,如果不是public,包名就是""
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();
//構(gòu)造代理類的類名: com.xxx.xxx.$Proxy0
String proxyName = proxyPkg + proxyClassNamePrefix + num;
/*
* Generate the specified proxy class.
*/
// 生成類的字節(jié)碼的字節(jié)數(shù)組
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, interfaces, accessFlags);
try {
// 通過native方法啸罢,用這個類加載器加載這個代理類到j(luò)vm中
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());
}
}
}
這里需要多解釋一些编检,ProxyGenerator.generateProxyClass(proxyName, interfaces, accessFlags); 在生成代理類時,內(nèi)部有一個generateConstructor方法扰才,專門給代理類繼承Proxy類允懂,并添加帶有InvocationHandler的構(gòu)造方法。這樣在創(chuàng)建代理類的實例對象時衩匣,通過InvocationHandler的回調(diào)來實現(xiàn)方法的擴展蕾总。
private ProxyGenerator.MethodInfo generateConstructor() throws IOException {
ProxyGenerator.MethodInfo var1 = new ProxyGenerator.MethodInfo("<init>", "(Ljava/lang/reflect/InvocationHandler;)V", 1);
DataOutputStream var2 = new DataOutputStream(var1.code);
this.code_aload(0, var2);
this.code_aload(1, var2);
var2.writeByte(183);
var2.writeShort(this.cp.getMethodRef("java/lang/reflect/Proxy", "<init>", "(Ljava/lang/reflect/InvocationHandler;)V"));
var2.writeByte(177);
var1.maxStack = 10;
var1.maxLocals = 2;
var1.declaredExceptions = new short[0];
return var1;
}
回到最上面的newProxyInstance方法,這里的cl就是生成代理類對象琅捏。
Class<?> cl = getProxyClass0(loader, intfs);
代理類生成后生百,通過調(diào)用帶有InvocationHandler的構(gòu)造方法,來newInstance對象柄延。
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});
至此蚀浆,基于JDK的動態(tài)代理對象生成過程就此完成。
總結(jié)
- JDK的動態(tài)代理內(nèi)部構(gòu)建了一個大的ConcurrentHashMap搜吧,存儲的是<類加載器, <接口列表, 代理類>>市俊。整個過程就是在圍繞這個大Map來緩存代理類。
- 創(chuàng)建代理類時滤奈,校驗了各種語法格式摆昧,生成了包名+$Proxy+數(shù)字的代理類,并且繼承了Proxy蜒程,補充了一個帶有InvocationHandler的構(gòu)造方法绅你。在創(chuàng)建代理類實例對象時,通過這個InvocationHandler對象進行方法回調(diào)搞糕,從而實現(xiàn)接口方法的擴展勇吊。
- 自定義的擴展就是實現(xiàn)InvocationHandler接口,實現(xiàn)invoke方法擴展窍仰,并將這個InvocationHandler對象傳給Proxy的構(gòu)造過程中汉规。
- 可以發(fā)現(xiàn),每次創(chuàng)建代理類對象時驹吮,都是通過緩存獲取代理類针史,并反射instance對象,有一定程度的性能影響碟狞。
附加:
生成的代理類大概長下面這樣:
public final class $Proxy0 extends Proxy implements ISomeInterface {
private static Method m1;
private static Method m3;
private static Method m2;
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 Object doSomething() throws {
try {
return (Object)super.h.invoke(this, m3, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
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 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"));
m3 = Class.forName("com.xxx.ISomeInterface").getMethod("doSomething");
m2 = Class.forName("java.lang.Object").getMethod("toString");
m0 = Class.forName("java.lang.Object").getMethod("hashCode");
} catch (NoSuchMethodException var2) {
throw new NoSuchMethodError(var2.getMessage());
} catch (ClassNotFoundException var3) {
throw new NoClassDefFoundError(var3.getMessage());
}
}
}