Java JDK動(dòng)態(tài)代理的基本原理詳細(xì)介紹
JDK動(dòng)態(tài)代理詳解
本文主要介紹JDK動(dòng)態(tài)代理的基本原理,讓大家更深刻的理解JDK Proxy,知其然知其所以然。明白JDK動(dòng)態(tài)代理真正的原理及其生成的過程,我們以后寫JDK Proxy可以不用去查demo,就可以徒手寫個(gè)完美的Proxy。下面首先來個(gè)簡單的Demo,后續(xù)的分析過程都依賴這個(gè)Demo去介紹,例子采用JDK1.8運(yùn)行。
JDK Proxy HelloWorld
package com.yao.proxy;
/**
* Created by robin
*/
public interface Helloworld {
void sayHello();
}
package com.yao.proxy;
import com.yao.HelloWorld;
/**
* Created by robin
*/
public class HelloworldImpl implements HelloWorld {
public void sayHello() {
System.out.print("hello world");
}
}
package com.yao.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
/**
* Created by robin
*/
public class MyInvocationHandler implements InvocationHandler{
private Object target;
public MyInvocationHandler(Object target) {
this.target=target;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("method :"+ method.getName()+" is invoked!");
return method.invoke(target,args);
}
}
package com.yao.proxy;
import com.yao.HelloWorld;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;
/**
* Created by robin
*/
public class JDKProxyTest {
public static void main(String[]args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
//這里有兩種寫法,我們采用略微復(fù)雜的一種寫法,這樣更有助于大家理解。
Class<?> proxyClass= Proxy.getProxyClass(JDKProxyTest.class.getClassLoader(),HelloWorld.class);
final Constructor<?> cons = proxyClass.getConstructor(InvocationHandler.class);
final InvocationHandler ih = new MyInvocationHandler(new HelloworldImpl());
HelloWorld helloWorld= (HelloWorld)cons.newInstance(ih);
helloWorld.sayHello();
//下面是更簡單的一種寫法,本質(zhì)上和上面是一樣的
/*
HelloWorld helloWorld=(HelloWorld)Proxy.
newProxyInstance(JDKProxyTest.class.getClassLoader(),
new Class<?>[]{HelloWorld.class},
new MyInvocationHandler(new HelloworldImpl()));
helloWorld.sayHello();
*/
}
}
運(yùn)行上面的代碼,這樣一個(gè)簡單的JDK Proxy就實(shí)現(xiàn)了。
代理生成過程
我們之所以天天叫JDK動(dòng)態(tài)代理,是因?yàn)檫@個(gè)代理class是由JDK在運(yùn)行時(shí)動(dòng)態(tài)幫我們生成。在解釋代理生成過程前,我們先把-Dsun.misc.ProxyGenerator.saveGeneratedFiles=true 這個(gè)參數(shù)加入到JVM 啟動(dòng)參數(shù)中,它的作用是幫我們把JDK動(dòng)態(tài)生成的proxy class 的字節(jié)碼保存到硬盤中,幫助我們查看具體生成proxy的內(nèi)容。我用的Intellij IDEA ,代理class生成后直接放在項(xiàng)目的根目錄下的,以具體的包名為目錄結(jié)構(gòu)。
代理類生成的過程主要包括兩部分:
- 代理類字節(jié)碼生成
- 把字節(jié)碼通過傳入的類加載器加載到虛擬機(jī)中
Proxy類的getProxyClass方法入口:需要傳入類加載器和interface

然后調(diào)用getProxyClass0方法,里面的注解解釋很清楚,如果實(shí)現(xiàn)當(dāng)前接口的代理類存在,直接從緩存中返回,如果不存在,則通過ProxyClassFactory來創(chuàng)建。這里可以明顯看到有對interface接口數(shù)量的限制,不能超過65535。其中proxyClassCache具體初始化信息如下:
proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
其中創(chuàng)建代理類的具體邏輯是通過ProxyClassFactory的apply方法來創(chuàng)建的。

ProxyClassFactory里的邏輯包括了包名的創(chuàng)建邏輯,調(diào)用ProxyGenerator. generateProxyClass生成代理類,把代理類字節(jié)碼加載到JVM。
1.包名生成邏輯默認(rèn)是com.sun.proxy,如果被代理類是 non-public proxy interface ,則用和被代理類接口一樣的包名,類名默認(rèn)是$Proxy 加上一個(gè)自增的整數(shù)值。
2.包名類名準(zhǔn)備好后,就是通過ProxyGenerator. generateProxyClass根據(jù)具體傳入的接口創(chuàng)建代理字節(jié)碼,-Dsun.misc.ProxyGenerator.saveGeneratedFiles=true 這個(gè)參數(shù)就是在該方法起到作用,如果為true則保存字節(jié)碼到磁盤。代理類中,所有的代理方法邏輯都一樣都是調(diào)用invocationHander的invoke方法,這個(gè)我們可以看后面具體代理反編譯結(jié)果。
3.把字節(jié)碼通過傳入的類加載器加載到JVM中: defineClass0(loader, proxyName,proxyClassFile, 0, proxyClassFile.length);。
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. 生成代理類的字節(jié)碼
* -Dsun.misc.ProxyGenerator.saveGeneratedFiles=true 在該部起作用
*/
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, interfaces, accessFlags);
try {
//加載到JVM中
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());
}
}
}
我們可以根據(jù)代理類的字節(jié)碼進(jìn)行反編譯,可以得到如下結(jié)果,其中HelloWorld只有sayHello方法,但是代理類中有四個(gè)方法 包括了Object上的三個(gè)方法:equals,toString,hashCode。
代理的大概結(jié)構(gòu)包括4部分:
- 靜態(tài)字段:被代理的接口所有方法都有一個(gè)對應(yīng)的靜態(tài)方法變量;
- 靜態(tài)塊:主要是通過反射初始化靜態(tài)方法變量;
- 具體每個(gè)代理方法:邏輯都差不多就是 h.invoke,主要是調(diào)用我們定義好的invocatinoHandler邏輯,觸發(fā)目標(biāo)對象target上對應(yīng)的方法;
- 構(gòu)造函數(shù):從這里傳入我們InvocationHandler邏輯;
package com.sun.proxy;
import com.yao.HelloWorld;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;
public final class $Proxy0 extends Proxy implements HelloWorld {
private static Method m1;
private static Method m3;
private static Method m2;
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 void sayHello() throws {
try {
super.h.invoke(this, m3, (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 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")});
m3 = Class.forName("com.yao.HelloWorld").getMethod("sayHello", new Class[0]);
m2 = Class.forName("java.lang.Object").getMethod("toString", 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());
}
}
}
常見問題:
1.toString() hashCode() equal()方法 調(diào)用邏輯:這個(gè)三個(gè)Object上的方法,如果被調(diào)用將和其他接口方法方法處理邏輯一樣,都會(huì)經(jīng)過invocationHandler邏輯,從上面的字節(jié)碼結(jié)果就可以明顯看出。其他Object上的方法將不會(huì)走代理處理邏輯,直接走Proxy繼承的Object上方法邏輯。
2.interface 含有equals,toString hashCode方法時(shí),和處理普通接口方法一樣,都會(huì)走invocation handler邏輯,以目標(biāo)對象重寫的邏輯為準(zhǔn)去觸發(fā)方法邏輯;
3.interface含有重復(fù)的方法簽名,以接口傳入順序?yàn)闇?zhǔn),誰在前面就用誰的方法,代理類中只會(huì)保留一個(gè),不會(huì)有重復(fù)的方法簽名;
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
- 深入理解java動(dòng)態(tài)代理的兩種實(shí)現(xiàn)方式(JDK/Cglib)
- java動(dòng)態(tài)代理(jdk與cglib)詳細(xì)解析
- Java JDK動(dòng)態(tài)代理(AOP)的實(shí)現(xiàn)原理與使用詳析
- java jdk動(dòng)態(tài)代理詳解
- Java JDK 動(dòng)態(tài)代理的使用方法示例
- java代理 jdk動(dòng)態(tài)代理應(yīng)用案列
- Java JDK動(dòng)態(tài)代理實(shí)現(xiàn)原理實(shí)例解析
- 詳解Java JDK動(dòng)態(tài)代理
- Java中JDK動(dòng)態(tài)代理的超詳細(xì)講解
相關(guān)文章
SpringBoot中Bean拷貝及工具類封裝的實(shí)現(xiàn)
本文主要介紹了SpringBoot中Bean拷貝及工具類封裝的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-05-05
詳解Java中使用泛型實(shí)現(xiàn)快速排序算法的方法
這篇文章主要介紹了Java中使用泛型實(shí)現(xiàn)快速排序算法的方法,快速排序的平均時(shí)間復(fù)雜度為(n\log n),文中的方法立足于基礎(chǔ)而并沒有考慮優(yōu)化處理,需要的朋友可以參考下2016-05-05
如何解決SpringBoot2.6及之后版本取消了循環(huán)依賴的支持問題
循環(huán)依賴指的是兩個(gè)或者多個(gè)bean之間相互依賴,形成一個(gè)閉環(huán),SpringBoot從2.6.0開始默認(rèn)不允許出現(xiàn)Bean循環(huán)引用,解決方案包括在全局配置文件設(shè)置允許循環(huán)引用存在、在SpringApplicationBuilder添加設(shè)置允許循環(huán)引用、構(gòu)造器注入2024-10-10
Springboot配置過濾器實(shí)現(xiàn)過程解析
這篇文章主要介紹了Springboot配置過濾器實(shí)現(xiàn)過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08
Java中設(shè)置session超時(shí)(失效)的三種方法
這篇文章主要介紹了Java中設(shè)置session超時(shí)(失效)的三種方法,本文講解了在web容器中設(shè)置、在工程的web.xml中設(shè)置、通過java代碼設(shè)置3種方法,需要的朋友可以參考下2015-07-07
詳解Java使用sqlite 數(shù)據(jù)庫如何生成db文件
這篇文章主要介紹了詳解Java 操作sqllite 數(shù)據(jù)庫如何生成db文件的相關(guān)資料,需要的朋友可以參考下2017-07-07
logback整合rabbitmq實(shí)現(xiàn)消息記錄日志的配置
這篇文章主要介紹了logback整合rabbitmq實(shí)現(xiàn)消息記錄日志的配置,本文通過示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-12-12

