JDK动态代理详解
本文主要介紹JDK動態代理的基本原理,讓大家更深刻的理解JDK Proxy,知其然知其所以然。明白JDK動態代理真正的原理及其生成的過程,我們以后寫JDK Proxy可以不用去查demo,就可以徒手寫個完美的Proxy。下面首先來個簡單的Demo,后續的分析過程都依賴這個Demo去介紹,例子采用JDK1.8運行。
JDK Proxy HelloWorld
| 1 2 3 4 5 6 7 | package com.yao.proxy; /** ?* Created by robin ?*/ public interface Helloworld { ????void sayHello(); } |
| 1 2 3 4 5 6 7 8 9 10 | package com.yao.proxy; import com.yao.HelloWorld; /** ?* Created by robin ?*/ public class HelloworldImpl implements HelloWorld { ????public void sayHello() { ????????System.out.print("hello world"); ????} } |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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); ????} } |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | 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 { ????????//這里有兩種寫法,我們采用略微復雜的一種寫法,這樣更有助于大家理解。 ????????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(); ????????//下面是更簡單的一種寫法,本質上和上面是一樣的 ????????/* ????????HelloWorld helloWorld=(HelloWorld)Proxy. ?????????????????newProxyInstance(JDKProxyTest.class.getClassLoader(), ????????????????????????new Class<?>[]{HelloWorld.class}, ????????????????????????new MyInvocationHandler(new HelloworldImpl())); ????????helloWorld.sayHello(); ????????*/ ????} } |
運行上面的代碼,這樣一個簡單的JDK Proxy就實現了。
代理生成過程
我們之所以天天叫JDK動態代理,是因為這個代理class是由JDK在運行時動態幫我們生成。在解釋代理生成過程前,我們先把-Dsun.misc.ProxyGenerator.saveGeneratedFiles=true 這個參數加入到JVM 啟動參數中,它的作用是幫我們把JDK動態生成的proxy class 的字節碼保存到硬盤中,幫助我們查看具體生成proxy的內容。我用的Intellij IDEA ,代理class生成后直接放在項目的根目錄下的,以具體的包名為目錄結構。
代理類生成的過程主要包括兩部分:
- 代理類字節碼生成
- 把字節碼通過傳入的類加載器加載到虛擬機中
Proxy類的getProxyClass方法入口:需要傳入類加載器和interface?
然后調用getProxyClass0方法,里面的注解解釋很清楚,如果實現當前接口的代理類存在,直接從緩存中返回,如果不存在,則通過ProxyClassFactory來創建。這里可以明顯看到有對interface接口數量的限制,不能超過65535。其中proxyClassCache具體初始化信息如下:
proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
其中創建代理類的具體邏輯是通過ProxyClassFactory的apply方法來創建的。
ProxyClassFactory里的邏輯包括了包名的創建邏輯,調用ProxyGenerator. generateProxyClass生成代理類,把代理類字節碼加載到JVM。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 | 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. 生成代理類的字節碼 ????????????* -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()); ???????????} ???????} ???} |
我們可以根據代理類的字節碼進行反編譯,可以得到如下結果,其中HelloWorld只有sayHello方法,但是代理類中有四個方法 包括了Object上的三個方法:equals,toString,hashCode。
代理的大概結構包括4部分:
- 靜態字段:被代理的接口所有方法都有一個對應的靜態方法變量;
- 靜態塊:主要是通過反射初始化靜態方法變量;
- 具體每個代理方法:邏輯都差不多就是 h.invoke,主要是調用我們定義好的invocatinoHandler邏輯,觸發目標對象target上對應的方法;
- 構造函數:從這里傳入我們InvocationHandler邏輯;
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | 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()); ????????} ????} } |
常見問題:
from:?http://www.importnew.com/23168.html
總結
- 上一篇: kafka学习笔记:知识点整理
- 下一篇: 浅谈WeakHashMap