Proxy
首先聲明早歇,此文是我自己閱讀JDK的動態(tài)代理記錄的筆記倾芝,可能對你沒有絲毫的幫助,請慎讀箭跳。 @_@!
使用JDK提供的動態(tài)代理晨另,需要java.lang.reflect.InvocationHandler
實現(xiàn).
public Object getInstance(Person target) throws Exception {
this.target = target;
Class<?> clazz = this.target.getClass();
//用來生成新的對象(使用字節(jié)碼重組)
return Proxy.newProxyInstance(clazz.getClassLoader(),
clazz.getInterfaces(), this);
}
這里使用了Proxy.newProxyInstance
來創(chuàng)建一個動態(tài)的代理類。進一步了解newProxyInstance
1.獲取代理類
Class<?> cl = getProxyClass0(loader, intfs);
2.創(chuàng)建代理類實例
調(diào)用構(gòu)造方法谱姓,創(chuàng)建并返回代理類的實例
//得到構(gòu)造方法
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});
進一步了解借尿,是JDK如何獲取代理類的
如何獲取代理類
private static Class<?> getProxyClass0(ClassLoader loader,
Class<?>... interfaces) {
//在編譯的class文件中,給類實現(xiàn)接口的記錄只有2byte屉来,
//因此路翻,這里限制實現(xiàn)接口的數(shù)量不能超過這個數(shù)量 2byte = 2^16 = 65535
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);
}
這里的ClassLoader
作用是,動態(tài)重組的字節(jié)碼茄靠,要動態(tài)加載到JVM上來茂契。
get
方法調(diào)用的是WeakCache
中的public V get(K key, P parameter)
方法。
WeakCache是Proxy中的一個靜態(tài)成員
private static final WeakCache<ClassLoader, Class<?>[], Class<?>>
proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
實例化時慨绳, 放入了 KeyFactory掉冶,和 ProxyClassFactory
WeakCache的get方法
public V get(K key, P parameter) {
Objects.requireNonNull(parameter);
expungeStaleEntries();
//構(gòu)建一個緩存Key
Object cacheKey = CacheKey.valueOf(key, refQueue);
// lazily install the 2nd level valuesMap for the particular cacheKey
// 從緩存中使用key獲取一次
ConcurrentMap<Object, Supplier<V>> valuesMap = map.get(cacheKey);
if (valuesMap == null) {
//如果為空時真竖, 用當(dāng)前key 創(chuàng)建一個 ConCurrentHashMap 并賦值給 valueMap
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
// 將Parameter中的 傳入的實現(xiàn)類接口 組成一個key 實現(xiàn)方式在
// Proxy中的內(nèi)部類 KeyFactory
Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
// 根據(jù)這個key,獲取到已經(jīng)上邊緩存中的 ConCurrentHashMap 這個map存的啥厌小,進一步探究 ↓
Supplier<V> supplier = valuesMap.get(subKey);
Factory factory = null;
while (true) {
if (supplier != null) {
// supplier might be a Factory or a CacheValue<V> instance
// 這個 supplier有可能是 Factory 或者 CacheValue
// 根據(jù)下方的代碼推導(dǎo)恢共,這里調(diào)用的是 Factory.get方法
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 = new Factory(key, parameter, subKey, valuesMap);
}
if (supplier == null) { //當(dāng)為空時 ,給一個值
//這里 pubIfAbsent 將subKey 和 factory放入到map璧亚,僅在subKey對應(yīng)的value為空時讨韭,才put進去,否則返回一個舊的 value(Factory)
supplier = valuesMap.putIfAbsent(subKey, factory);
if (supplier == null) {
// successfully installed Factory
//將工廠賦值給 本應(yīng)該從map中獲取到的值上邊
supplier = factory;
}
// else retry with winning supplier
} else {
//返回一個 有 factory的 supplier 癣蟋,這是個舊的Factory
// 此處調(diào)用 替換方案 將獲取出來 的 supplier 用新new的factory 替換
/** replace 舊值為空或者 與傳入的舊值是相同的時候 才進行替換拐袜,并返回舊
的值否則返回空 */
if (valuesMap.replace(subKey, supplier, factory)) { //當(dāng)有返回值,表示 //舊的替換成功了 則將 supplier 替換成新的factory
// successfully replaced
// cleared CacheEntry / unsuccessful Factory
// with our Factory
supplier = factory;
} else {
// retry with current supplier
// 如果沒替換成功梢薪,重試獲取一次蹬铺。并回到loop的第一行
supplier = valuesMap.get(subKey);
}
}
}
}
//模擬第二遍的流程,假設(shè)此時已經(jīng)獲取到了 supplier(Factory)
//調(diào)用一個Factory.get
if (supplier != null) {
// supplier might be a Factory or a CacheValue<V> instance
// 這里調(diào)用 Factory的 get方法
V value = supplier.get();
if (value != null) {
return value;
}
}
KeyFactory的實現(xiàn)
private static final class KeyFactory
implements BiFunction<ClassLoader, Class<?>[], Object>
{
@Override
public Object apply(ClassLoader classLoader, Class<?>[] interfaces) {
switch (interfaces.length) {
case 1: return new Key1(interfaces[0]); // the most frequent
case 2: return new Key2(interfaces[0], interfaces[1]);
case 0: return key0;
default: return new KeyX(interfaces);
}
}
}
Factory.get()方法
@Override
public synchronized V get() { // serialize access
// re-check
Supplier<V> supplier = valuesMap.get(subKey);
if (supplier != this) {
return null;
}
// else still us (supplier == this)
// create new value
V value = null;
try {
// 用傳入的 ClassLoader和 需要被代理的對象秉撇,調(diào)用 valueFactory.apply方法 根據(jù)上下文
// 可以看出 這個 valueFactory其實是 ProxyClassFactory 類型甜攀,因此,這里的apply實際上就是
// ProxyClassFactory的 apply方法琐馆,這個方法的功能是规阀,重組字節(jié)碼,并用ClassLoader加載到 JVM然后返回
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) {
Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.length);
//遍歷實現(xiàn)的接口瘦麸,檢查類加載器加載的接口與 傳入的接口一致性
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. JDK要求被代理的對象一定要實現(xiàn)一個接口谁撼,這里確認是否為一個interface
*/
if (!interfaceClass.isInterface()) {
throw new IllegalArgumentException(
interfaceClass.getName() + " is not an interface");
}
/*
* Verify that this interface is not a duplicate.
* 用Map檢查接口,是否實現(xiàn)接口重復(fù)性
*/
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
//構(gòu)建包名稱
proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
}
/*
* Choose a name for the proxy class to generate.
*/
//構(gòu)建 代理對象的對象名稱滋饲,例如 com.sun.proxy.$Proxy0這里按照JDK代理對象的規(guī)范
// 添加上$在target對象名前邊厉碟,然后用 一個計數(shù)器來標記target生成的次數(shù)
long num = nextUniqueNumber.getAndIncrement();
String proxyName = proxyPkg + proxyClassNamePrefix + num;
/*
* Generate the specified proxy class.
*/
//調(diào)用 ProxyGenerator 重組一個 java文件的byte數(shù)組
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, interfaces, accessFlags);
try {
//調(diào)用類加載的方式,將byte數(shù)組動態(tài)的加載到JVM
return defineClass0(loader, proxyName,
proxyClassFile, 0, proxyClassFile.length);
} catch (ClassFormatError e) {
throw new IllegalArgumentException(e.toString());
}
}
按照以上豐富的操作屠缭,就是JDK實現(xiàn)動態(tài)代理的方式箍鼓,放一個動態(tài)生成的代理類的內(nèi)容
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;
import org.rate.pattern.proxy.Person;
public final class $Proxy0 extends Proxy implements Person {
//將目標類中的方法統(tǒng)計出來,定義到成員中
private static Method m1;
private static Method m4;
private static Method m2;
private static Method m5;
private static Method m3;
private static Method m0;
//調(diào)用構(gòu)造方法時呵曹,將 invocationHandler 傳入到款咖,這個變量會保存到 Proxy中的變量h
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);
}
}
/** target類的方法 1 其他就不寫備注了 */
public final void findLove() throws {
try {
//調(diào)用方法時,走h也就是構(gòu)造方法給的h 在結(jié)合 開頭提起的
////用來生成新的對象(使用字節(jié)碼重組)
//return Proxy.newProxyInstance(clazz.getClassLoader(),
// clazz.getInterfaces(), this);
// 代理類這里需要實現(xiàn) InvocationHandler 并重寫 Invoker方法
// 進一步查看 重寫的 invoker方法
super.h.invoke(this, m4, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
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 zufangzi() throws {
try {
super.h.invoke(this, m5, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
public final void findJob() throws {
try {
super.h.invoke(this, m3, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
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"));
m4 = Class.forName("org.rate.pattern.proxy.Person").getMethod("findLove");
m2 = Class.forName("java.lang.Object").getMethod("toString");
m5 = Class.forName("org.rate.pattern.proxy.Person").getMethod("zufangzi");
m3 = Class.forName("org.rate.pattern.proxy.Person").getMethod("findJob");
m0 = Class.forName("java.lang.Object").getMethod("hashCode");
} catch (NoSuchMethodException var2) {
throw new NoSuchMethodError(var2.getMessage());
} catch (ClassNotFoundException var3) {
throw new NoClassDefFoundError(var3.getMessage());
}
}
}
實現(xiàn)的代理類
public class ProxyImple implements InvocationHandler {
private Person target;
public Object getInstance(Person target) throws Exception {
this.target = target;
Class<?> clazz = this.target.getClass();
//用來生成新的對象(使用字節(jié)碼重組)
return Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), this);
}
//這里就是反射出來的方法 實際上, invoke的this.target可以替換成 medhos跨新, 結(jié)果是一樣的
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("方法執(zhí)行前的操作1");
System.out.println("方法執(zhí)行前的操作2");
method.invoke(this.target, args);
System.out.println("方法執(zhí)行后的操作1");
System.out.println("方法執(zhí)行后的操作2");
return null;
}
}
至此富腊,JDK的動態(tài)代理源碼就到此了。