淺說動态代理
關于java的代理模式,此處不過多講解。所謂代理模式是指用戶端并不直接調用實際的對象,而是通過調用代理,來間接的調用實際的對象。動态代理指被代理者委托代理者完成相應的功能,是攔截器的一種實作方式,其用于攔截類或接口,内部可通過判斷實作對某個方法的攔截。
日常使用中可能經常需要在方法調用時進行攔截,如調用前記錄一下調用開始時間,調用結束後記錄結束時間,就可以很友善的計算出調用方法的業務邏輯處理耗時。
動态代理使用
簡單的看下最簡單的使用:
- 編寫一個接口:
package my.java.reflect.test;
public interface Animal {
void sayHello();
}
- 委托類
public class Dog implements Animal {
public void sayHello() {
System.out.println("wang wang!");
}
}
- 攔截器
package my.java.reflect.test;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class MyInvocationHandler implements InvocationHandler {
private Object target;
public Object bind(Object realObj) {
this.target = realObj;
Class<?>[] interfaces = target.getClass().getInterfaces();
ClassLoader classLoader = this.getClass().getClassLoader();
return Proxy.newProxyInstance(classLoader, interfaces, this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("proxy method");
return method.invoke(target, args);
}
}
- 測試類
package my.java.reflect.test;
import org.junit.Test;
public class ProxyTest {
@Test
public void testNewProxyInstance() {
Dog dog = new Dog();
Animal proxy = (Animal) new MyInvocationHandler().bind(dog);
proxy.sayHello();
}
}
- 輸出
proxy method
wang wang!
動态代理原理總結
之是以将原理先總結了,因為希望把原理先用最簡潔的語言說清楚,再來深入分析,否則在深入分析階段粘貼過多的源碼可能會導緻閱讀興趣下降。
- 通過
方法得到代理對象執行個體;Proxy#newProxyInstance
- 這個代理對象有着和委托類一模一樣的方法;
- 當調用代理對象執行個體的方法時,這個執行個體會調用你實作
裡的InvocationHandler
方法。invoke
而這裡,最複雜的顯然是得到代理對象執行個體了,怎麼得到的呢?來,看看源碼!
動态代理原理
要了解java動态代理的原理隻要從
Proxy#newProxyInstance
入手即可。
- 先看newProxyInstance方法,關注有中文注釋的地方即可
@CallerSensitive
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
{
if (h == null) {// 沒有實作InvocationHandler,直接失敗
throw new NullPointerException();
}
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對象
*/
Class<?> cl = getProxyClass0(loader, intfs);
/*
* Invoke its constructor with the designated invocation handler.
*/
try {
// 拿到代理對象的構造方法
final Constructor<?> cons = cl.getConstructor(constructorParams);
final InvocationHandler ih = h;
if (sm != null && ProxyAccessHelper.needsNewInstanceCheck(cl)) {
// create proxy instance with doPrivilege as the proxy class may
// implement non-public interfaces that requires a special permission
return AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
return newInstance(cons, ih);
}
});
} else {
// 構造出代理對象執行個體
return newInstance(cons, ih);
}
} catch (NoSuchMethodException e) {
throw new InternalError(e.toString());
}
}
// 利用反射調用構造方法,産生代理執行個體,沒什麼好說的
private static Object newInstance(Constructor<?> cons, InvocationHandler h) {
try {
return cons.newInstance(new Object[] {h} );
} catch (IllegalAccessException | InstantiationException e) {
throw new InternalError(e.toString());
} catch (InvocationTargetException e) {
Throwable t = e.getCause();
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
} else {
throw new InternalError(t.toString());
}
}
}
以上這段代碼的核心在
/*
* Look up or generate the designated proxy class.
* 查找或者生成代理類的Class對象
*/
Class<?> cl = getProxyClass0(loader, intfs);
- 檢視
方法getProxyClass0
private static Class<?> getProxyClass0(ClassLoader loader,
Class<?>... interfaces) {
if (interfaces.length > 65535) {// 你的類如果實作了超過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
// 如果委托類的接口已經存在于緩存中,則傳回,否則利用ProxyClassFactory産生一個新的代理類的Class對象
return proxyClassCache.get(loader, interfaces);
}
這段話的核心很顯然就是
proxyClassCache.get(loader, interfaces)
,其中
proxyClassCache
是一個緩存:
/**
* a cache of proxy classes
*/
private static final WeakCache<ClassLoader, Class<?>[], Class<?>>
proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
- 繼續看
,對應的是proxyClassCache.get(loader, interfaces)
,一大段代碼就為了傳回一個代理類的java.lang.reflect.WeakCache<K, P, V>#get
對象,關注中文注釋處即可:Class
public V get(K key, P parameter) {
Objects.requireNonNull(parameter);
expungeStaleEntries();
Object cacheKey = CacheKey.valueOf(key, refQueue);
// 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;
}
}
// 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;
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);
}
}
}
}
這段代碼的核心就在
V value = supplier.get();
,通過這段代碼,代理類的
Class
的對象就出來了。
-
,這段代碼還是在subKeyFactory.apply(key, parameter)
裡:WeakCache
@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;
// 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;
}
回看
proxyClassCache
可以知道
valueFacotry
對應的是
ProxyClassFactory
類,這是
java.reflect.Proxy
的内部類:
@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);// 看下接口對應的類檔案有沒有被ClassLoader加載
} 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
/*
* 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)) {// 接口不是public的,截取包名,保證代理類跟委托類同一個包下
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) {// 是public的接口,拼接成com.sun.proxy$Proxy,再拼接一個數字
// 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);
try {
// 根據位元組碼生成代理類Class對象,native方法,看過類加載器的童鞋應該不陌生
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
生成代理類的位元組碼數組,接着将位元組碼封裝成
Class
對象,就是代理類的
Class
對象了。生成位元組碼數組的代碼就不詳細說了。
- 将位元組碼數組寫到檔案裡檢視一下:
byte[] data = ProxyGenerator.generateProxyClass(“Animal$Proxy”, new Class[] { Animal.class });
FileOutputStream out = new FileOutputStream("Animal$Proxy.class");
out.write(data);
- 利用jd-gui反編譯工具可以看看代理類的源碼:
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;
public final class Animal$Proxy extends Proxy implements my.java.reflect.test.Animal {
private static Method m3;
private static Method m1;
private static Method m0;
private static Method m2;
public Animal$Proxy(InvocationHandler paramInvocationHandler) {
super(paramInvocationHandler);
}
public final void sayHello() {
try {
this.h.invoke(this, m3, null);
return;
} catch (Error | RuntimeException localError) {
throw localError;
} catch (Throwable localThrowable) {
throw new UndeclaredThrowableException(localThrowable);
}
}
public final boolean equals(Object paramObject) {
try {
return ((Boolean) this.h.invoke(this, m1, new Object[] { paramObject })).booleanValue();
} catch (Error | RuntimeException localError) {
throw localError;
} catch (Throwable localThrowable) {
throw new UndeclaredThrowableException(localThrowable);
}
}
public final int hashCode() {
try {
return ((Integer) this.h.invoke(this, m0, null)).intValue();
} catch (Error | RuntimeException localError) {
throw localError;
} catch (Throwable localThrowable) {
throw new UndeclaredThrowableException(localThrowable);
}
}
public final String toString() {
try {
return (String) this.h.invoke(this, m2, null);
} catch (Error | RuntimeException localError) {
throw localError;
} catch (Throwable localThrowable) {
throw new UndeclaredThrowableException(localThrowable);
}
}
static {
try {
m3 = Class.forName("my.java.reflect.test.Animal").getMethod("sayHello", new Class[0]);
m1 = Class.forName("java.lang.Object").getMethod("equals",
new Class[] { Class.forName("java.lang.Object") });
m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
return;
} catch (NoSuchMethodException localNoSuchMethodException) {
throw new NoSuchMethodError(localNoSuchMethodException.getMessage());
} catch (ClassNotFoundException localClassNotFoundException) {
throw new NoClassDefFoundError(localClassNotFoundException.getMessage());
}
}
}
可以看到生成的代理類有一個構造方法,參數是
InvocationHandler
,然後回看我們第一步分析的時候,得到代理類的
Class
對象後,會通過反射得到代理類的構造方法,接着調用構造方法,參數就是
InvocationHandler
。
在代理類的源碼裡,最值得注意的就是
m3
,這個對應的是
Animal
的
sayHello
方法,當我們通過
MyInvocationHandler#bind
方法得到代理對象執行個體後,調用代理對象
Animal$Proxy
sayHello
方法,就會執行:
public final void sayHello() {
try {
this.h.invoke(this, m3, null);
return;
} catch (Error | RuntimeException localError) {
throw localError;
} catch (Throwable localThrowable) {
throw new UndeclaredThrowableException(localThrowable);
}
}
正好是我們在
MyInvocationHandler
實作的
invoke
方法,這樣就完成了代理的功能。
用一個總結收尾
-
Proxy#newProxyInstance
-
InvocationHandler
invoke
這裡面無疑第一步是最複雜的,這裡大概經曆了:
- 利用參數中的接口,通過緩存或者利用
生成位元組碼并生成代理類的ProxyGenerator
對象;Class
- 通過反射得到代理對象的構造方法;
- 通過構造方法和
參數通過反射執行個體化出代理對象執行個體。InvocationHandler