過程說明:動態生成目標接口的 Class 代理類,這個代理類是實現了接口中的所有方法。然後再把此class加載到內存中。調用代理類方法的時候代理類去調用實際對象方法。
1. 分析生產的過程
Proxy#newProxyInstance 中的代碼就描述上面說的過程,
- 生成代理類 class 對象
- 構建代理類實例
public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) throws IllegalArgumentException {
...
//依據接口生產代理對象的 class 對象
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)
,此方法裏面只需要關注 proxyClassCache
(WeakCache類) 這個成員變量。此類是用於緩存代理對象的。
/**
* a cache of proxy classes
*/
private static final WeakCache<ClassLoader, Class<?>[], Class<?>>
proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
構建 proxyClassCache 有2個參數,其中關鍵的是 ProxyClassFactory ①
WeakCache#get
方法是核心方法,這裏是構建並且緩存對象。
public V get(K key, P parameter) {
...
//關鍵
while (true) {
if (supplier != null) {
// supplier might be a Factory or a CacheValue<V> instance
// 這裏已經說明白了,第一次的話都是 Factory 提供的實例
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 後,我們關注一下 Factory 的實現
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);
}
}
}
...
}
下面來到 Factory#get
方法中,其實核心就是 valueFactory.apply(key, parameter)
,其實就是調用了 ProxyClassFactory ①
private final class Factory implements Supplier<V> {
@Override
public synchronized V get() {
...
// serialize access
// create new value
V value = null;
try {
//核心就是 valueFactory.apply(key, parameter),其實就是調用了 ProxyClassFactory ①
value = Objects.requireNonNull(valueFactory.apply(key, parameter));
} finally {
if (value == null) { // remove us on failure
valuesMap.remove(subKey, this);
}
}
...
return value;
}
}
現在我們目光回到 ProxyClassFactory#apply
方法
public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) {
//這裏就生產了代理類的字節碼流
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());
}
}
也就是說,我們也可以手動去調用 ProxyGenerator#generateProxyClass
去生成我們的字節碼。
1.1 小結
通過以上的分析,其實JDK動態代理核心就是 ProxyGenerator#generateProxyClass
,更多的旁枝末節更多是輔助性的,比如緩存等。
2. 如何實現對目標方法的調用
我們回顧一下動態代理是如何使用的,
//調用生成代理類,其中關鍵需要傳入interfaces和InvocationHandler。
Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)
其中 InvocationHandler
我們會這樣實現
// 其中我們會實現這個方法,在這個方法裏面調用實際的代理對象
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable{
//前置邏輯
Object obj = method.invoke(被代理的對象實例,args);
//後置邏輯
return obj;
}
2.1 解析生成的代理類
瞭解完成後如何調用,我們看一下生成的 class 反編譯看看。
我們定義一個接口 ICar
public interface ICar {
void start();
void run();
void stop();
}
通過動態代理生成的 class
import fun.lsof.javacore.proxy.dynamic.ICar;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;
public final class Proxy1 extends Proxy implements ICar {
// 擁有具體對象的方法對象
private static Method m1;
private static Method m3;
private static Method m2;
private static Method m5;
private static Method m4;
private static Method m0;
// 默認構造函數需要傳入 InvocationHandler
public Proxy1(InvocationHandler paramInvocationHandler) {
super(paramInvocationHandler);
}
// 實現的方法
public final void start() {
try {
this.h.invoke(this, m4, null);
return;
} catch (Error | RuntimeException localError) {
throw localError;
} catch (Throwable localThrowable) {
throw new UndeclaredThrowableException(localThrowable);
}
}
// 實現的方法
public final void run() {
try {
this.h.invoke(this, m3, null);
return;
} catch (Error | RuntimeException localError) {
throw localError;
} catch (Throwable localThrowable) {
throw new UndeclaredThrowableException(localThrowable);
}
}
// 實現的方法
public final void stop() {
try {
this.h.invoke(this, m5, null);
return;
} catch (Error | RuntimeException localError) {
throw localError;
} catch (Throwable localThrowable) {
throw new UndeclaredThrowableException(localThrowable);
}
}
// 初始化全局變量中的方法,通過反射拿到Method對象
static {
try {
m3 = Class.forName("fun.lsof.javacore.proxy.dynamic.ICar").getMethod("run", new Class[0]);
m5 = Class.forName("fun.lsof.javacore.proxy.dynamic.ICar").getMethod("stop", new Class[0]);
m4 = Class.forName("fun.lsof.javacore.proxy.dynamic.ICar").getMethod("start", new Class[0]);
m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[]{Class.forName("java.lang.Object")});
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());
}
}
public final boolean equals(Object paramObject) {
...
}
public final int hashCode() {
...
}
public final String toString() {
...
}
}
看到以上自動生成的代碼,Proxy1
初始化的時候,就會加載靜態函數,其中靜態代碼塊中是枚舉了所有接口(ICar)中類的方法。擁有接口中的方法是爲了反射可以調用。再看到 start、run、stop 方法,每個方法都回調了 InvocationHandler#invoke方法。從而達到對方法的前後增強
// 提供具體代理的對象 proxy、代理方法的 method、代理方法的參數 args
invoke(Object proxy, Method method, Object[] args)
不依靠Proxy來實現動態代理實現方法:https://github.com/JerryDai90/java-case/tree/master/java-core/proxy/src/main/java/fun/lsof/javacore/proxy/dynamic
3. 總結
其實 JDK 的動態代理就是動態生成字節碼而已,然後再使用反射技術對接口中的方法進行引用。通過反射即可調用被代理對象的方法。從而達到代理的目的。
4. 擴展
高仿一個 ProxyFactory,Github:https://github.com/JerryDai90/java-case/tree/master/java-core/proxy/src/main/java/fun/lsof/javacore/proxy/dynamic/aop