動態代理的使用
調用Proxy#newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)
即可完成動態代理的使用;
//: 接口類
interface ITest{
void fun(int arg);
}
//: 接口實現類
static class ITestImpl implements ITest{
@Override
public void fun(int arg) {
}
}
//: 代理類
static class TestProxy<T> implements InvocationHandler {
private T object;
public TestProxy(T object) {
this.object = object;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object object = method.invoke(this.object, args);
return object;
}
}
//: main函數
public static void main(String[] args) {
ITestImpl iTestImpl = new ITestImpl();
TestProxy testProxy = new TestProxy<ITest>(iTestImpl);
ITest iTest = (ITest) Proxy.newProxyInstance(
iTestImpl.getClass().getClassLoader(),
new Class[]{ITest.class},
testProxy
);
iTest.fun(2);
}
Proxy#newProxyInstance
方法生成一個ITest
的代理類實例(只看函數名也可猜出這個靜態方法的功能)。具體的實例實現交由一個InvocationHandler
實例處理,這個InvocationHandler
也可定義爲一個匿名內部類。
代理類的產生
接下來,一起探究這個動態代理API,是如何生成這個動態代理實例的;
首先進入newProxyInstance
內部:
newProxyInstance解析
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
{
/*
* Look up or generate the designated proxy class.
*/
//獲取或產生一個代理類的`class對象`
Class<?> cl = getProxyClass0(loader, intfs)
final Constructor<?> cons = cl.getConstructor(constructorParams);
final InvocationHandler ih = h;
cons.setAccessible(true);
//利用反射將h作爲傳參生成,代理類對象
return cons.newInstance(new Object[]{h});
}
getProxyClass0方法解析
下面開始探究代理類
實例的產生;
//: Proxy.java
/**
* a cache of proxy classes
*/
private static final WeakCache<ClassLoader, Class<?>[], Class<?>>
proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
/**
* 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
return proxyClassCache.get(loader, interfaces);
}
通過上述代碼可知這個class實例
在一個WeakCache
的緩存實例中獲取,所以需要進入WeakCache
中進一步分析:
//: WeakCache.java
public WeakCache(BiFunction<K, P, ?> subKeyFactory,
BiFunction<K, P, V> valueFactory) {
this.subKeyFactory = Objects.requireNonNull(subKeyFactory);
this.valueFactory = Objects.requireNonNull(valueFactory);
}
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);
}
}
}
}
結合Proxy.java
中的代碼可知,這裏的subKeyFactory
是一個KeyFactory
對象,valueFactory
是一個ProxyClassFactory
對象,請牢記這兩個對象和其對應的類型。
在回到proxyClassCache.get(loader, interfaces);
,所以要繼續分析WeakCache#get(K key, P parameter)
方法;
在WeakCache#get(K key, P parameter)
方法中,大多數工作是緩存的實現和緩存的讀取,在當前代理的接口第一次進入的時候,將生產一個Factory
實例, WeakCache#get(K key, P parameter)
方法簡化後的可表示爲:
factory = new Factory(key, parameter, subKey, valuesMap);
Supplier supplier = factory;
V value = supplier.get();
if (value != null) {
return value;
}
其中Factory
爲WeakCache
的內部類,可想而知Factory
將協助外部來讀寫WeakCache
的內部信息;
再來看Supplier#get()
方法在Factory#get()
中的具體實現:
@Override
public synchronized V get() { // serialize access
V value = null;
value = Objects.requireNonNull(valueFactory.apply(key, parameter));
return value;
}
這裏的Factory
對WeakCache#valueFactory
進行了操作,通過apply
方法拿到最後的代理實例,而WeakCache#valueFactory
是一個ProxyClassFactory
實例,所以需要再分享ProxyClassFactory#apply()
方法:
//: ProxyClassFactory.java
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());
}
}
}
private static native Class<?> defineClass0(ClassLoader loader, String name,
byte[] b, int off, int len);
動態代理類生成的代理類長啥樣
將proxyClassFile
字符數組寫入文件便可以瀏覽動態代理生成的代理類文件;
最終生成的class
文件代碼爲:
final class $Proxy0 extends Proxy implements ITest {
private static Method m1;
private static Method m2;
private static Method m3;
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 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 void fun(int var1) throws {
try {
super.h.invoke(this, m3, new Object[]{var1});
} catch (RuntimeException | Error var3) {
throw var3;
} catch (Throwable var4) {
throw new UndeclaredThrowableException(var4);
}
}
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("com.example.www.Test1$ITest").getMethod("fun", 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());
}
}
}
但是Jvm並沒生成對應的class文件,而是直接通過defineClass0(ClassLoader loader, String name,byte[] b, int off, int len)
方法將byte
數組載入,並返回一個Class
對象。
從生成的class
文件可以看出$Proxy0
即爲最終的代理類,然後使用橋接模式
調用構造函數傳過來的InvocationHandler
的invoke
函數,並將方法和參數等信息傳入。