過程說明:動(dòng)態(tài)生成目標(biāo)接口的 Class 代理類,這個(gè)代理類是實(shí)現(xiàn)了接口中的所有方法诈胜。然后再把此class加載到內(nèi)存中。調(diào)用代理類方法的時(shí)候代理類去調(diào)用實(shí)際對象方法。
1. 分析生產(chǎn)的過程
Proxy#newProxyInstance 中的代碼就描述上面說的過程言缤,
- 生成代理類 class 對象
- 構(gòu)建代理類實(shí)例
public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) throws IllegalArgumentException {
...
//依據(jù)接口生產(chǎn)代理對象的 class 對象
Class<?> cl = getProxyClass0(loader, intfs);
...
//生成代理對象實(shí)例
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)
,此方法里面只需要關(guān)注 proxyClassCache
(WeakCache類) 這個(gè)成員變量禁灼。此類是用于緩存代理對象的管挟。
/**
* a cache of proxy classes
*/
private static final WeakCache<ClassLoader, Class<?>[], Class<?>>
proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
構(gòu)建 proxyClassCache 有2個(gè)參數(shù),其中關(guān)鍵的是 ProxyClassFactory ①
WeakCache#get
方法是核心方法弄捕,這里是構(gòu)建并且緩存對象僻孝。
public V get(K key, P parameter) {
...
//關(guān)鍵
while (true) {
if (supplier != null) {
// supplier might be a Factory or a CacheValue<V> instance
// 這里已經(jīng)說明白了,第一次的話都是 Factory 提供的實(shí)例
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) {
//關(guān)鍵在此處守谓,構(gòu)建完成 Factory 后皮璧,我們關(guān)注一下 Factory 的實(shí)現(xiàn)
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
方法中,其實(shí)核心就是 valueFactory.apply(key, parameter)
分飞,其實(shí)就是調(diào)用了 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)悴务,其實(shí)就是調(diào)用了 ProxyClassFactory ①
value = Objects.requireNonNull(valueFactory.apply(key, parameter));
} finally {
if (value == null) { // remove us on failure
valuesMap.remove(subKey, this);
}
}
...
return value;
}
}
現(xiàn)在我們目光回到 ProxyClassFactory#apply
方法
public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) {
//這里就生產(chǎn)了代理類的字節(jié)碼流
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());
}
}
也就是說,我們也可以手動(dòng)去調(diào)用 ProxyGenerator#generateProxyClass
去生成我們的字節(jié)碼譬猫。
1.1 小結(jié)
通過以上的分析讯檐,其實(shí)JDK動(dòng)態(tài)代理核心就是 ProxyGenerator#generateProxyClass
,更多的旁枝末節(jié)更多是輔助性的染服,比如緩存等别洪。
2. 如何實(shí)現(xiàn)對目標(biāo)方法的調(diào)用
我們回顧一下動(dòng)態(tài)代理是如何使用的,
//調(diào)用生成代理類柳刮,其中關(guān)鍵需要傳入interfaces和InvocationHandler挖垛。
Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)
其中 InvocationHandler
我們會(huì)這樣實(shí)現(xiàn)
// 其中我們會(huì)實(shí)現(xiàn)這個(gè)方法,在這個(gè)方法里面調(diào)用實(shí)際的代理對象
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable{
//前置邏輯
Object obj = method.invoke(被代理的對象實(shí)例秉颗,args);
//后置邏輯
return obj;
}
2.1 解析生成的代理類
了解完成后如何調(diào)用痢毒,我們看一下生成的 class 反編譯看看。
我們定義一個(gè)接口 ICar
public interface ICar {
void start();
void run();
void stop();
}
通過動(dòng)態(tài)代理生成的 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;
// 默認(rèn)構(gòu)造函數(shù)需要傳入 InvocationHandler
public Proxy1(InvocationHandler paramInvocationHandler) {
super(paramInvocationHandler);
}
// 實(shí)現(xiàn)的方法
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);
}
}
// 實(shí)現(xiàn)的方法
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);
}
}
// 實(shí)現(xiàn)的方法
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() {
...
}
}
看到以上自動(dòng)生成的代碼哪替,Proxy1
初始化的時(shí)候,就會(huì)加載靜態(tài)函數(shù)菇怀,其中靜態(tài)代碼塊中是枚舉了所有接口(ICar)中類的方法凭舶。擁有接口中的方法是為了反射可以調(diào)用晌块。再看到 start、run帅霜、stop 方法匆背,每個(gè)方法都回調(diào)了 InvocationHandler#invoke方法。從而達(dá)到對方法的前后增強(qiáng)
// 提供具體代理的對象 proxy身冀、代理方法的 method靠汁、代理方法的參數(shù) args
invoke(Object proxy, Method method, Object[] args)
不依靠Proxy來實(shí)現(xiàn)動(dòng)態(tài)代理實(shí)現(xiàn)方法:https://github.com/JerryDai90/java-case/tree/master/java-core/proxy/src/main/java/fun/lsof/javacore/proxy/dynamic
3. 總結(jié)
其實(shí) JDK 的動(dòng)態(tài)代理就是動(dòng)態(tài)生成字節(jié)碼而已,然后再使用反射技術(shù)對接口中的方法進(jìn)行引用闽铐。通過反射即可調(diào)用被代理對象的方法蝶怔。從而達(dá)到代理的目的。
4. 擴(kuò)展
高仿一個(gè) ProxyFactory兄墅,Github:https://github.com/JerryDai90/java-case/tree/master/java-core/proxy/src/main/java/fun/lsof/javacore/proxy/dynamic/aop