java 1.8 動態(tài)代理源碼深度分析
JDK8動態(tài)代理源碼分析
動態(tài)代理的基本使用就不詳細介紹了:
例子:
class proxyed implements pro{
@Override
public void text() {
System.err.println("本方法");
}
}
interface pro {
void text();
}
public class JavaProxy implements InvocationHandler {
private Object source;
public JavaProxy(Object source) {
super();
this.source = source;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("before");
Object invoke = method.invoke(source, args);
System.out.println("after");
return invoke;
}
public Object getProxy(){
return Proxy.newProxyInstance(getClass().getClassLoader(), source.getClass().getInterfaces(), this);
}
public static void main(String[] args) throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException {
//第一種,自己寫
//1.設(shè)置saveGeneratedFiles值為true則生成 class字節(jié)碼文件方便分析
System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
//2.獲取動態(tài)代理類
Class proxyClazz = Proxy.getProxyClass(pro.class.getClassLoader(),pro.class);
//3.獲得代理類的構(gòu)造函數(shù),并傳入?yún)?shù)類型InvocationHandler.class
Constructor constructor = proxyClazz.getConstructor(InvocationHandler.class);
//4.通過構(gòu)造函數(shù)來創(chuàng)建動態(tài)代理對象,將自定義的InvocationHandler實例傳入
pro iHello = (pro) constructor.newInstance(new JavaProxy(new proxyed()));
//5.通過代理對象調(diào)用目標方法
iHello.text();
//第二種,調(diào)用JDK提供的方法,實現(xiàn)了2~4步
Proxy.newProxyInstance(JavaProxy.class.getClassLoader(),proxyed.class.getInterfaces(),new JavaProxy(new proxyed()));
}
}
入口:newProxyInstance
public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) throws IllegalArgumentException {
//Objects.requireNonNull 判空方法,之后所有的單純的判斷null并拋異常,都是此方法
Objects.requireNonNull(h);
//clone 類實現(xiàn)的所有接口
final Class<?>[] intfs = interfaces.clone();
//獲取當前系統(tǒng)安全接口
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
//Reflection.getCallerClass返回調(diào)用該方法的方法的調(diào)用類;loader:接口的類加載器
//進行包訪問權(quán)限、類加載器權(quán)限等檢查
checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
}
/*
* Look up or generate the designated proxy class.
* 查找或生成代理類
*/
Class<?> cl = getProxyClass0(loader, intfs);
/*
* Invoke its constructor with the designated invocation handler.
* 使用指定的調(diào)用處理程序調(diào)用它的構(gòu)造函數(shù)
*/
try {
if (sm != null) {
checkNewProxyPermission(Reflection.getCallerClass(), cl);
}
//獲取構(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});
} catch (IllegalAccessException|InstantiationException e) {
throw new InternalError(e.toString(), e);
} catch (InvocationTargetException e) {
Throwable t = e.getCause();
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
} else {
throw new InternalError(t.toString(), t);
}
} catch (NoSuchMethodException e) {
throw new InternalError(e.toString(), e);
}
}
從上面的分析中可以看出,newProxyInstance幫我們執(zhí)行了生成代理類----獲取構(gòu)造器----生成代理對象這三步;
我們重點分析生成代理類
getProxyClass0
/**
* a cache of proxy classes:動態(tài)代理類的弱緩存容器
* KeyFactory:根據(jù)接口的數(shù)量,映射一個最佳的key生成函數(shù),其中表示接口的類對象被弱引用;也就是key對象被弱引用繼承自WeakReference(key0、key1、key2、keyX),保存接口密鑰(hash值)
* ProxyClassFactory:生成動態(tài)類的工廠
* 注意,兩個都實現(xiàn)了BiFunction<ClassLoader, Class<?>[], Object>接口
*/
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.
* 生成代理類,調(diào)用前必須進行 checkProxyAccess權(quán)限檢查,所以newProxyInstance進行了權(quán)限檢查
*/
private static Class<?> getProxyClass0(ClassLoader loader, Class<?>... interfaces) {
//實現(xiàn)接口的最大數(shù)量<65535;誰寫的類能實現(xiàn)這么多接口
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);
}
proxyClassCache.get
public V get(K key, P parameter) {
//key:類加載器;parameter:接口數(shù)組
Objects.requireNonNull(parameter);
//清除已經(jīng)被GC回收的弱引用
expungeStaleEntries();
//CacheKey弱引用類,refQueue已經(jīng)被回收的弱引用隊列;構(gòu)建一個CacheKey
Object cacheKey = CacheKey.valueOf(key, refQueue);
//map一級緩存,獲取valuesMap二級緩存
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;
}
}
// subKeyFactory類型是KeyFactory,apply返回表示接口的key
Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
//Factory 實現(xiàn)了supplier,我們實際是獲取緩存中的Factory,調(diào)用其get方法
Supplier<V> supplier = valuesMap.get(subKey);
Factory factory = null;
//下面用到了 CAS+重試 實現(xiàn)的多線程安全的 非阻塞算法
while (true) {
if (supplier != null) {
// 只需要知道,最終會調(diào)用get方法,此supplier可能是緩存中取出來的,也可能是Factory新new出來的
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);
}
}
}
}
supplier.get
這個方法中會調(diào)用ProxyClassFactory的apply方法,就不過多介紹
ProxyClassFactory.apply
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.
* 確保接口沒重復(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.
* 驗證所有非公共的接口在同一個包內(nèi);公共的就無需處理
*/
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.
* proxyClassNamePrefix = $Proxy
* nextUniqueNumber 是一個原子類,確保多線程安全,防止類名重復(fù),類似于:$Proxy0,$Proxy1......
*/
long num = nextUniqueNumber.getAndIncrement();
String proxyName = proxyPkg + proxyClassNamePrefix + num;
/*
* Generate the specified proxy class.
* 生成類字節(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());
}
}
ProxyGenerator.generateProxyClass
public static byte[] generateProxyClass(final String name, Class<?>[] interfaces, int accessFlags) {
ProxyGenerator gen = new ProxyGenerator(name, interfaces, accessFlags);
//真正生成字節(jié)碼的方法
final byte[] classFile = gen.generateClassFile();
//如果saveGeneratedFiles為true 則生成字節(jié)碼文件,所以在開始我們要設(shè)置這個參數(shù)
//當然,也可以通過返回的bytes自己輸出
if (saveGeneratedFiles) {
java.security.AccessController.doPrivileged( new java.security.PrivilegedAction<Void>() {
public Void run() {
try {
int i = name.lastIndexOf('.');
Path path;
if (i > 0) {
Path dir = Paths.get(name.substring(0, i).replace('.', File.separatorChar));
Files.createDirectories(dir);
path = dir.resolve(name.substring(i+1, name.length()) + ".class");
} else {
path = Paths.get(name + ".class");
}
Files.write(path, classFile);
return null;
} catch (IOException e) {
throw new InternalError( "I/O exception saving generated file: " + e);
}
}
});
}
return classFile;
}
最終方法
private byte[] generateClassFile() {
/* ============================================================
* Step 1: Assemble ProxyMethod objects for all methods to generate proxy dispatching code for.
* 步驟1:為所有方法生成代理調(diào)度代碼,將代理方法對象集合起來。
*/
//增加 hashcode、equals、toString方法
addProxyMethod(hashCodeMethod, Object.class);
addProxyMethod(equalsMethod, Object.class);
addProxyMethod(toStringMethod, Object.class);
//增加接口方法
for (Class<?> intf : interfaces) {
for (Method m : intf.getMethods()) {
addProxyMethod(m, intf);
}
}
/*
* 驗證方法簽名相同的一組方法,返回值類型是否相同;意思就是重寫方法要方法簽名和返回值一樣
*/
for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
checkReturnTypes(sigmethods);
}
/* ============================================================
* Step 2: Assemble FieldInfo and MethodInfo structs for all of fields and methods in the class we are generating.
* 為類中的方法生成字段信息和方法信息
*/
try {
//增加構(gòu)造方法
methods.add(generateConstructor());
for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
for (ProxyMethod pm : sigmethods) {
// add static field for method's Method object
fields.add(new FieldInfo(pm.methodFieldName,
"Ljava/lang/reflect/Method;",
ACC_PRIVATE | ACC_STATIC));
// generate code for proxy method and add it
methods.add(pm.generateMethod());
}
}
//增加靜態(tài)初始化信息
methods.add(generateStaticInitializer());
} catch (IOException e) {
throw new InternalError("unexpected I/O Exception", e);
}
if (methods.size() > 65535) {
throw new IllegalArgumentException("method limit exceeded");
}
if (fields.size() > 65535) {
throw new IllegalArgumentException("field limit exceeded");
}
/* ============================================================
* Step 3: Write the final class file.
* 步驟3:編寫最終類文件
*/
/*
* Make sure that constant pool indexes are reserved for the following items before starting to write the final class file.
* 在開始編寫最終類文件之前,確保為下面的項目保留常量池索引。
*/
cp.getClass(dotToSlash(className));
cp.getClass(superclassName);
for (Class<?> intf: interfaces) {
cp.getClass(dotToSlash(intf.getName()));
}
/*
* Disallow new constant pool additions beyond this point, since we are about to write the final constant pool table.
* 設(shè)置只讀,在這之前不允許在常量池中增加信息,因為要寫常量池表
*/
cp.setReadOnly();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(bout);
try {
// u4 magic;
dout.writeInt(0xCAFEBABE);
// u2 次要版本;
dout.writeShort(CLASSFILE_MINOR_VERSION);
// u2 主版本
dout.writeShort(CLASSFILE_MAJOR_VERSION);
cp.write(dout); // (write constant pool)
// u2 訪問標識;
dout.writeShort(accessFlags);
// u2 本類名;
dout.writeShort(cp.getClass(dotToSlash(className)));
// u2 父類名;
dout.writeShort(cp.getClass(superclassName));
// u2 接口;
dout.writeShort(interfaces.length);
// u2 interfaces[interfaces_count];
for (Class<?> intf : interfaces) {
dout.writeShort(cp.getClass(
dotToSlash(intf.getName())));
}
// u2 字段;
dout.writeShort(fields.size());
// field_info fields[fields_count];
for (FieldInfo f : fields) {
f.write(dout);
}
// u2 方法;
dout.writeShort(methods.size());
// method_info methods[methods_count];
for (MethodInfo m : methods) {
m.write(dout);
}
// u2 類文件屬性:對于代理類來說沒有類文件屬性;
dout.writeShort(0); // (no ClassFile attributes for proxy classes)
} catch (IOException e) {
throw new InternalError("unexpected I/O Exception", e);
}
return bout.toByteArray();
}
生成的字節(jié)碼反編譯
final class $Proxy0 extends Proxy implements pro {
//fields
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})).booleanValue();
} 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 text() throws {
try {
//實際就是調(diào)用代理類的invoke方法
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)).intValue();
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
static {
try {
//這里每個方法對象 和類的實際方法綁定
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]);
m3 = Class.forName("spring.commons.api.study.CreateModel.pro").getMethod("text", new Class[0]);
m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
} catch (NoSuchMethodException var2) {
throw new NoSuchMethodError(var2.getMessage());
} catch (ClassNotFoundException var3) {
throw new NoClassDefFoundError(var3.getMessage());
}
}
}
以上這篇java 1.8 動態(tài)代理源碼深度分析就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Spring實戰(zhàn)之使用XML方式管理聲明式事務(wù)操作示例
這篇文章主要介紹了Spring實戰(zhàn)之使用XML方式管理聲明式事務(wù)操作,結(jié)合實例形式詳細分析了Spring XML方式管理聲明式事務(wù)具體步驟、配置、接口及使用技巧,需要的朋友可以參考下2020-01-01
Spring Boot如何實現(xiàn)定時任務(wù)的動態(tài)增刪啟停詳解
這篇文章主要給大家介紹了關(guān)于Spring Boot如何實現(xiàn)定時任務(wù)的動態(tài)增刪啟停的相關(guān)資料,文中通過示例代碼以及圖文介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友們下面來一起學(xué)習學(xué)習吧2020-07-07
基于Springboot+Netty實現(xiàn)rpc的方法 附demo
這篇文章主要介紹了基于Springboot+Netty實現(xiàn)rpc功能,在父項目中引入相關(guān)依賴結(jié)合實例代碼給大家介紹的非常詳細,對大家的學(xué)習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-02-02
springboot多數(shù)據(jù)源使用@Qualifier自動注入無效的解決
這篇文章主要介紹了springboot多數(shù)據(jù)源使用@Qualifier自動注入無效的解決,具有很好的參考價值,希望對大家有所幫助。也希望大家多多支持腳本之家2021-11-11

