前言
之前對(duì)動(dòng)態(tài)代理了解僅僅在于表層,一直覺(jué)得高不可攀,今天點(diǎn)開(kāi)了 Proxy 類(lèi),欲知故事如何,需 Read The Source Code,再加上看一些別人的文章,對(duì)照著自己對(duì)源碼的理解,形成此文,通俗易懂,保你看后對(duì)動(dòng)態(tài)代理又有了更加深入的理解
先看一個(gè)例子熟悉一下吧
先定義接口,之后我們?cè)倏矗瑸槭裁碕DK不能代理類(lèi),只能代理接口
public interface AddService {
/**
* <p>Test method</p>
*
* @param a number a
* @param b number b
* @return sum of a and b
*/
int add(int a, int b);
}
實(shí)現(xiàn)類(lèi)
public class AddServiceImpl implements AddService {
@Override
public int add(int a, int b) {
return a + b;
}
}
Handler,繼承自InvocationHandler,該接口只有一個(gè)方法 invoke,你只需要實(shí)現(xiàn)它,然后利用反射 Object invoke = method.invoke(addService, args); 返回接口return invoke; 其他的你想干什么都行,當(dāng)然你也完全改變這個(gè)這個(gè)實(shí)現(xiàn),返回一些別的啥,壞事也是可以的。getProxy方法里面調(diào)用Proxy.newProxyInstance 獲取一個(gè)代理對(duì)象
public class AddServiceHandler implements InvocationHandler {
private AddService addService;
public AddServiceHandler(AddService addService) {
this.addService = addService;
}
public AddService getProxy() {
return (AddService) Proxy.newProxyInstance(addService.getClass().getClassLoader(),
addService.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("before");
Object invoke = method.invoke(addService, args);
System.out.println("after");
return invoke;
}
}
使用,首先獲取創(chuàng)建實(shí)例對(duì)象,然后構(gòu)造一個(gè)Handler,再通過(guò)Handler獲取Proxy 對(duì)象,再調(diào)用接口的方法。我們一切的疑問(wèn),可能就在 getProxy,他到底返回了什么東西,能夠讓我們?cè)僬{(diào)用接口方法的時(shí)候,執(zhí)行的卻是 實(shí)現(xiàn)的Service 的方法,并且加了一些其它實(shí)現(xiàn),聰明的你可能會(huì)說(shuō),這用靜態(tài)代理依然能夠?qū)崿F(xiàn),并且要比動(dòng)態(tài)代理來(lái)得簡(jiǎn)單,為什么還要這樣復(fù)雜的實(shí)現(xiàn)。我現(xiàn)在能想到的是,靜態(tài)代理的話(huà),你可能需要為每一個(gè)代理接口實(shí)現(xiàn)一個(gè)代理 Handler,然而 InvocationHandler 的話(huà),你只需要為類(lèi)似的請(qǐng)求實(shí)現(xiàn)一個(gè)Handler,為程序的擴(kuò)展提供了大大的空間。
@Test
public void dynamicProxyTest() {
AddService service = new AddServiceImpl();
AddServiceHandler addServiceHandler = new AddServiceHandler(service);
AddService proxy = addServiceHandler.getProxy();
Assert.assertEquals(3, proxy.add(1, 2));
}
看到這里,我們有很多疑問(wèn)
- Proxy.newProxyInstance() 返回的是什么東西
- invoke 方法到底在哪調(diào)用
- 我們?cè)?target 里面沒(méi)有看到其它任何附帶生成的 class,系統(tǒng)到底是怎么做的呢
那我們就要好好看看這些方法的實(shí)現(xiàn)原理
Proxy.newProxyInstance
public class Proxy implements java.io.Serializable{}
private 的構(gòu)造方法,里面有一個(gè) InvocationHandler,這個(gè)就是我們傳入的 Handler,另外還有一個(gè) proxyClassCache,一個(gè)代理類(lèi)的緩存對(duì)象,我暫時(shí)不打算展開(kāi)講這個(gè)東西,還沒(méi)搞明白,現(xiàn)在需要記住,這個(gè)存放這系統(tǒng)幫我們生成的代理類(lèi),用了WeakReference 實(shí)現(xiàn), GC 的時(shí)候會(huì)被回收。
里面有兩個(gè)參數(shù)傳過(guò)去,KeyFactory() 先不管,ProxyClassFactory() 這個(gè)很重要,我們之后遇到了再說(shuō)
/** parameter types of a proxy class constructor */
private static final Class<?>[] constructorParams =
{ InvocationHandler.class };
/**
* a cache of proxy classes
*/
private static final WeakCache<ClassLoader, Class<?>[], Class<?>>
proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
/**
* the invocation handler for this proxy instance.
* @serial
*/
protected InvocationHandler h;
/**
* Prohibits instantiation.
*/
private Proxy() {
}
為了理解方便,我將一些無(wú)關(guān)精要的代碼剔除,留下最重要的兩個(gè)方法,getProxyClass0(loader, intfs) 根據(jù)loader和intfs 獲取代理類(lèi),通過(guò)這個(gè)方法我們獲得一個(gè)新的類(lèi)字節(jié)碼,這個(gè)類(lèi)是運(yùn)行時(shí)生成的,通過(guò)這個(gè)代理類(lèi),getConstructor 獲取構(gòu)造對(duì)象,調(diào)用newInstance創(chuàng)建一個(gè)實(shí)例對(duì)象,newInstance是可以傳參的,只需要調(diào)用 constructor 的構(gòu)造方法參數(shù)必須是 InvocationHandler.class,所以我們傳的是 this 對(duì)象。
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
{
/*
* Look up or generate the designated proxy class.
*/
Class<?> cl = getProxyClass0(loader, intfs);
final Constructor<?> cons = cl.getConstructor(constructorParams);
return cons.newInstance(new Object[]{h});
}
65535 限制,這個(gè)get 比較高級(jí),直接從緩存拿,剛開(kāi)始看到可能覺(jué)得有點(diǎn)納悶,這個(gè) proxyClassCache 之前遇到過(guò)了
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);
}
get方法首先創(chuàng)建一個(gè) valuesMap,獲取subKey,里面比較重要的就是subKeyFactory.apply(key, parameter),這個(gè)方法會(huì)幫我們生成代理類(lèi)的subKey,另外之后會(huì)建立一個(gè)Factory,當(dāng)使用get 的時(shí)候,便是真正生成 代理類(lèi)的時(shí)候
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);
}
}
}
}
ProxyClassFactory apply 不可不看,首先加載接口,然后使用ProxyGenerator.generateProxyClass 生成Class 字節(jié)碼文件,最后再調(diào)用 defineClass0 對(duì)其加載后返回關(guān)鍵字,作為key,之后再根據(jù)這個(gè)key獲取到真正的class 對(duì)象,到這里,Proxy類(lèi)已經(jīng)生成好,并且加載好了,直接返回,這個(gè)類(lèi)是動(dòng)態(tài)生成的,留在內(nèi)存的數(shù)據(jù)
private static final class ProxyClassFactory
implements BiFunction<ClassLoader, Class<?>[], Class<?>>
{
// prefix for all proxy class names
private static final String proxyClassNamePrefix = "$Proxy";
// next number to use for generation of unique proxy class names
private static final AtomicLong nextUniqueNumber = new AtomicLong();
@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.
*/
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());
}
}
}
那我們可以調(diào)用ProxyGenerator.generateProxyClass來(lái)看一次下這個(gè)生成的類(lèi),把它寫(xiě)到文件里,這個(gè)類(lèi)大概就是這個(gè)樣子,就是我們通過(guò)getProxy獲取到的實(shí)際類(lèi),之后就簡(jiǎn)單了,可以清楚的看到里面熟悉的add方法,是通過(guò)調(diào)用了 invoke 來(lái)實(shí)現(xiàn)的
public final class $Proxy11 extends Proxy implements Service {
private static Method m1;
private static Method m2;
private static Method m3;
private static Method m0;
public $Proxy11(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 int add(int var1, int var2) throws {
try {
return (Integer)super.h.invoke(this, m3, new Object[]{var1, var2});
} catch (RuntimeException | Error var4) {
throw var4;
} catch (Throwable var5) {
throw new UndeclaredThrowableException(var5);
}
}
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("proxy.Service").getMethod("add", Integer.TYPE, Integer.TYPE);
m0 = Class.forName("java.lang.Object").getMethod("hashCode");
} catch (NoSuchMethodException var2) {
throw new NoSuchMethodError(var2.getMessage());
} catch (ClassNotFoundException var3) {
throw new NoClassDefFoundError(var3.getMessage());
}
}
}
至此,大部分邏輯已經(jīng)搞清楚了,那我們大概知道了為什么這個(gè)過(guò)程要比直接創(chuàng)建對(duì)象要慢,那是因?yàn)樗谝淮蔚臅r(shí)候需要?jiǎng)討B(tài)的去創(chuàng)建字節(jié)碼,然后進(jìn)行加載,初始化......雖然有緩存,但是由于使用了 WeakReference,GC后有可能會(huì)被回收,那么就得重新加載,一定程度上會(huì)降低效率,所以一般情況下,我們盡量避免這種動(dòng)態(tài)生成類(lèi)的方式,而是用在編譯時(shí)生成類(lèi)的方式取代,這便是 APT 技術(shù)的精髓。
小結(jié)
上面三個(gè)小問(wèn)題都已經(jīng)弄清楚了吧,現(xiàn)在對(duì)動(dòng)態(tài)代理更加了解了些,另外一類(lèi) CGLIB,更改字節(jié)碼的技術(shù)之后有時(shí)間會(huì)再去看
歡迎討論~~~