JDK動態代理實現原理

之前雖然會用JDK的動態代理,但是有些問題卻一直沒有搞明白。比如說:InvocationHandler的invoke方法是由誰來調用的,代理對象是怎麼生成的,直到前幾個星期才把這些問題全部搞明白了。 
    廢話不多說了,先來看一下JDK的動態是怎麼用的。 

Java代碼  收藏代碼
  1. package dynamic.proxy;   
  2.   
  3. import java.lang.reflect.InvocationHandler;  
  4. import java.lang.reflect.Method;  
  5. import java.lang.reflect.Proxy;  
  6.   
  7. /** 
  8.  * 實現自己的InvocationHandler 
  9.  * @author zyb 
  10.  * @since 2012-8-9 
  11.  * 
  12.  */  
  13. public class MyInvocationHandler implements InvocationHandler {  
  14.       
  15.     // 目標對象   
  16.     private Object target;  
  17.       
  18.     /** 
  19.      * 構造方法 
  20.      * @param target 目標對象  
  21.      */  
  22.     public MyInvocationHandler(Object target) {  
  23.         super();  
  24.         this.target = target;  
  25.     }  
  26.   
  27.   
  28.     /** 
  29.      * 執行目標對象的方法 
  30.      */  
  31.     public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {  
  32.           
  33.         // 在目標對象的方法執行之前簡單的打印一下  
  34.         System.out.println("------------------before------------------");  
  35.           
  36.         // 執行目標對象的方法  
  37.         Object result = method.invoke(target, args);  
  38.           
  39.         // 在目標對象的方法執行之後簡單的打印一下  
  40.         System.out.println("-------------------after------------------");  
  41.           
  42.         return result;  
  43.     }  
  44.   
  45.     /** 
  46.      * 獲取目標對象的代理對象 
  47.      * @return 代理對象 
  48.      */  
  49.     public Object getProxy() {  
  50.         return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),   
  51.                 target.getClass().getInterfaces(), this);  
  52.     }  
  53. }  
  54.   
  55. package dynamic.proxy;  
  56.   
  57. /** 
  58.  * 目標對象實現的接口,用JDK來生成代理對象一定要實現一個接口 
  59.  * @author zyb 
  60.  * @since 2012-8-9 
  61.  * 
  62.  */  
  63. public interface UserService {  
  64.   
  65.     /** 
  66.      * 目標方法  
  67.      */  
  68.     public abstract void add();  
  69.   
  70. }  
  71.   
  72. package dynamic.proxy;   
  73.   
  74. /** 
  75.  * 目標對象 
  76.  * @author zyb 
  77.  * @since 2012-8-9 
  78.  * 
  79.  */  
  80. public class UserServiceImpl implements UserService {  
  81.   
  82.     /* (non-Javadoc) 
  83.      * @see dynamic.proxy.UserService#add() 
  84.      */  
  85.     public void add() {  
  86.         System.out.println("--------------------add---------------");  
  87.     }  
  88. }  
  89.   
  90. package dynamic.proxy;   
  91.   
  92. import org.junit.Test;  
  93.   
  94. /** 
  95.  * 動態代理測試類 
  96.  * @author zyb 
  97.  * @since 2012-8-9 
  98.  * 
  99.  */  
  100. public class ProxyTest {  
  101.   
  102.     @Test  
  103.     public void testProxy() throws Throwable {  
  104.         // 實例化目標對象  
  105.         UserService userService = new UserServiceImpl();  
  106.           
  107.         // 實例化InvocationHandler  
  108.         MyInvocationHandler invocationHandler = new MyInvocationHandler(userService);  
  109.           
  110.         // 根據目標對象生成代理對象  
  111.         UserService proxy = (UserService) invocationHandler.getProxy();  
  112.           
  113.         // 調用代理對象的方法  
  114.         proxy.add();  
  115.           
  116.     }  
  117. }  


執行結果如下: 
------------------before------------------ 
--------------------add--------------- 
-------------------after------------------
 

   用起來是很簡單吧,其實這裏基本上就是AOP的一個簡單實現了,在目標對象的方法執行之前和執行之後進行了增強。Spring的AOP實現其實也是用了Proxy和InvocationHandler這兩個東西的。 

    用起來是比較簡單,但是如果能知道它背後做了些什麼手腳,那就更好不過了。首先來看一下JDK是怎樣生成代理對象的。既然生成代理對象是用的Proxy類的靜態方newProxyInstance,那麼我們就去它的源碼裏看一下它到底都做了些什麼? 
Java代碼  收藏代碼
  1. /** 
  2.  * loader:類加載器 
  3.  * interfaces:目標對象實現的接口 
  4.  * h:InvocationHandler的實現類 
  5.  */  
  6. public static Object newProxyInstance(ClassLoader loader,  
  7.                       Class<?>[] interfaces,  
  8.                       InvocationHandler h)  
  9.     throws IllegalArgumentException  
  10.     {  
  11.     if (h == null) {  
  12.         throw new NullPointerException();  
  13.     }  
  14.   
  15.     /* 
  16.      * Look up or generate the designated proxy class. 
  17.      */  
  18.     Class cl = getProxyClass(loader, interfaces);  
  19.   
  20.     /* 
  21.      * Invoke its constructor with the designated invocation handler. 
  22.      */  
  23.     try {  
  24.             // 調用代理對象的構造方法(也就是$Proxy0(InvocationHandler h))  
  25.         Constructor cons = cl.getConstructor(constructorParams);  
  26.             // 生成代理類的實例並把MyInvocationHandler的實例傳給它的構造方法  
  27.         return (Object) cons.newInstance(new Object[] { h });  
  28.     } catch (NoSuchMethodException e) {  
  29.         throw new InternalError(e.toString());  
  30.     } catch (IllegalAccessException e) {  
  31.         throw new InternalError(e.toString());  
  32.     } catch (InstantiationException e) {  
  33.         throw new InternalError(e.toString());  
  34.     } catch (InvocationTargetException e) {  
  35.         throw new InternalError(e.toString());  
  36.     }  
  37.     }  


   我們再進去getProxyClass方法看一下 
Java代碼  收藏代碼
  1. public static Class<?> getProxyClass(ClassLoader loader,   
  2.                                          Class<?>... interfaces)  
  3.     throws IllegalArgumentException  
  4.     {  
  5.     // 如果目標類實現的接口數大於65535個則拋出異常(我XX,誰會寫這麼NB的代碼啊?)  
  6.     if (interfaces.length > 65535) {  
  7.         throw new IllegalArgumentException("interface limit exceeded");  
  8.     }  
  9.   
  10.     // 聲明代理對象所代表的Class對象(有點拗口)  
  11.     Class proxyClass = null;  
  12.   
  13.     String[] interfaceNames = new String[interfaces.length];  
  14.   
  15.     Set interfaceSet = new HashSet();   // for detecting duplicates  
  16.   
  17.     // 遍歷目標類所實現的接口  
  18.     for (int i = 0; i < interfaces.length; i++) {  
  19.           
  20.         // 拿到目標類實現的接口的名稱  
  21.         String interfaceName = interfaces[i].getName();  
  22.         Class interfaceClass = null;  
  23.         try {  
  24.         // 加載目標類實現的接口到內存中  
  25.         interfaceClass = Class.forName(interfaceName, false, loader);  
  26.         } catch (ClassNotFoundException e) {  
  27.         }  
  28.         if (interfaceClass != interfaces[i]) {  
  29.         throw new IllegalArgumentException(  
  30.             interfaces[i] + " is not visible from class loader");  
  31.         }  
  32.   
  33.         // 中間省略了一些無關緊要的代碼 .......  
  34.           
  35.         // 把目標類實現的接口代表的Class對象放到Set中  
  36.         interfaceSet.add(interfaceClass);  
  37.   
  38.         interfaceNames[i] = interfaceName;  
  39.     }  
  40.   
  41.     // 把目標類實現的接口名稱作爲緩存(Map)中的key  
  42.     Object key = Arrays.asList(interfaceNames);  
  43.   
  44.     Map cache;  
  45.       
  46.     synchronized (loaderToCache) {  
  47.         // 從緩存中獲取cache  
  48.         cache = (Map) loaderToCache.get(loader);  
  49.         if (cache == null) {  
  50.         // 如果獲取不到,則新建地個HashMap實例  
  51.         cache = new HashMap();  
  52.         // 把HashMap實例和當前加載器放到緩存中  
  53.         loaderToCache.put(loader, cache);  
  54.         }  
  55.   
  56.     }  
  57.   
  58.     synchronized (cache) {  
  59.   
  60.         do {  
  61.         // 根據接口的名稱從緩存中獲取對象  
  62.         Object value = cache.get(key);  
  63.         if (value instanceof Reference) {  
  64.             proxyClass = (Class) ((Reference) value).get();  
  65.         }  
  66.         if (proxyClass != null) {  
  67.             // 如果代理對象的Class實例已經存在,則直接返回  
  68.             return proxyClass;  
  69.         } else if (value == pendingGenerationMarker) {  
  70.             try {  
  71.             cache.wait();  
  72.             } catch (InterruptedException e) {  
  73.             }  
  74.             continue;  
  75.         } else {  
  76.             cache.put(key, pendingGenerationMarker);  
  77.             break;  
  78.         }  
  79.         } while (true);  
  80.     }  
  81.   
  82.     try {  
  83.         // 中間省略了一些代碼 .......  
  84.           
  85.         // 這裏就是動態生成代理對象的最關鍵的地方  
  86.         byte[] proxyClassFile = ProxyGenerator.generateProxyClass(  
  87.             proxyName, interfaces);  
  88.         try {  
  89.             // 根據代理類的字節碼生成代理類的實例  
  90.             proxyClass = defineClass0(loader, proxyName,  
  91.             proxyClassFile, 0, proxyClassFile.length);  
  92.         } catch (ClassFormatError e) {  
  93.             throw new IllegalArgumentException(e.toString());  
  94.         }  
  95.         }  
  96.         // add to set of all generated proxy classes, for isProxyClass  
  97.         proxyClasses.put(proxyClass, null);  
  98.   
  99.     }   
  100.     // 中間省略了一些代碼 .......  
  101.       
  102.     return proxyClass;  
  103.     }  


進去ProxyGenerator類的靜態方法generateProxyClass,這裏是真正生成代理類class字節碼的地方。 
Java代碼  收藏代碼
  1. public static byte[] generateProxyClass(final String name,  
  2.                                            Class[] interfaces)  
  3.    {  
  4.        ProxyGenerator gen = new ProxyGenerator(name, interfaces);  
  5.     // 這裏動態生成代理類的字節碼,由於比較複雜就不進去看了  
  6.        final byte[] classFile = gen.generateClassFile();  
  7.   
  8.     // 如果saveGeneratedFiles的值爲true,則會把所生成的代理類的字節碼保存到硬盤上  
  9.        if (saveGeneratedFiles) {  
  10.            java.security.AccessController.doPrivileged(  
  11.            new java.security.PrivilegedAction<Void>() {  
  12.                public Void run() {  
  13.                    try {  
  14.                        FileOutputStream file =  
  15.                            new FileOutputStream(dotToSlash(name) + ".class");  
  16.                        file.write(classFile);  
  17.                        file.close();  
  18.                        return null;  
  19.                    } catch (IOException e) {  
  20.                        throw new InternalError(  
  21.                            "I/O exception saving generated file: " + e);  
  22.                    }  
  23.                }  
  24.            });  
  25.        }  
  26.   
  27.     // 返回代理類的字節碼  
  28.        return classFile;  
  29.    }  


現在,JDK是怎樣動態生成代理類的字節的原理已經一目瞭然了。 

好了,再來解決另外一個問題,那就是由誰來調用InvocationHandler的invoke方法的。要解決這個問題就要看一下JDK到底爲我們生成了一個什麼東西。用以下代碼可以獲取到JDK爲我們生成的字節碼並寫到硬盤中。 
Java代碼  收藏代碼
  1. package dynamic.proxy;   
  2.   
  3. import java.io.FileOutputStream;  
  4. import java.io.IOException;  
  5.   
  6. import sun.misc.ProxyGenerator;  
  7.   
  8. /** 
  9.  * 代理類的生成工具 
  10.  * @author zyb 
  11.  * @since 2012-8-9 
  12.  */  
  13. public class ProxyGeneratorUtils {  
  14.   
  15.     /** 
  16.      * 把代理類的字節碼寫到硬盤上 
  17.      * @param path 保存路徑 
  18.      */  
  19.     public static void writeProxyClassToHardDisk(String path) {  
  20.         // 第一種方法,這種方式在剛纔分析ProxyGenerator時已經知道了  
  21.         // System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", true);  
  22.           
  23.         // 第二種方法  
  24.           
  25.         // 獲取代理類的字節碼  
  26.         byte[] classFile = ProxyGenerator.generateProxyClass("$Proxy11", UserServiceImpl.class.getInterfaces());  
  27.           
  28.         FileOutputStream out = null;  
  29.           
  30.         try {  
  31.             out = new FileOutputStream(path);  
  32.             out.write(classFile);  
  33.             out.flush();  
  34.         } catch (Exception e) {  
  35.             e.printStackTrace();  
  36.         } finally {  
  37.             try {  
  38.                 out.close();  
  39.             } catch (IOException e) {  
  40.                 e.printStackTrace();  
  41.             }  
  42.         }  
  43.     }  
  44. }  
  45.   
  46. package dynamic.proxy;   
  47.   
  48. import org.junit.Test;  
  49.   
  50. /** 
  51.  * 動態代理測試類 
  52.  * @author zyb 
  53.  * @since 2012-8-9 
  54.  * 
  55.  */  
  56. public class ProxyTest {  
  57.   
  58.     @Test  
  59.     public void testProxy() throws Throwable {  
  60.         // 實例化目標對象  
  61.         UserService userService = new UserServiceImpl();  
  62.           
  63.         // 實例化InvocationHandler  
  64.         MyInvocationHandler invocationHandler = new MyInvocationHandler(userService);  
  65.           
  66.         // 根據目標對象生成代理對象  
  67.         UserService proxy = (UserService) invocationHandler.getProxy();  
  68.           
  69.         // 調用代理對象的方法  
  70.         proxy.add();  
  71.           
  72.     }  
  73.       
  74.     @Test  
  75.     public void testGenerateProxyClass() {  
  76.         ProxyGeneratorUtils.writeProxyClassToHardDisk("F:/$Proxy11.class");  
  77.     }  
  78. }  


通過以上代碼,就可以在F盤上生成一個$Proxy.class文件了,現在用反編譯工具來看一下這個class文件裏面的內容。 
Java代碼  收藏代碼
  1. // Decompiled by DJ v3.11.11.95 Copyright 2009 Atanas Neshkov  Date: 2012/8/9 20:11:32  
  2. // Home Page: http://members.fortunecity.com/neshkov/dj.html  http://www.neshkov.com/dj.html - Check often for new version!  
  3. // Decompiler options: packimports(3)   
  4.   
  5. import dynamic.proxy.UserService;  
  6. import java.lang.reflect.*;  
  7.   
  8. public final class $Proxy11 extends Proxy  
  9.     implements UserService  
  10. {  
  11.   
  12.     // 構造方法,參數就是剛纔傳過來的MyInvocationHandler類的實例  
  13.     public $Proxy11(InvocationHandler invocationhandler)  
  14.     {  
  15.         super(invocationhandler);  
  16.     }  
  17.   
  18.     public final boolean equals(Object obj)  
  19.     {  
  20.         try  
  21.         {  
  22.             return ((Boolean)super.h.invoke(this, m1, new Object[] {  
  23.                 obj  
  24.             })).booleanValue();  
  25.         }  
  26.         catch(Error _ex) { }  
  27.         catch(Throwable throwable)  
  28.         {  
  29.             throw new UndeclaredThrowableException(throwable);  
  30.         }  
  31.     }  
  32.   
  33.     /** 
  34.      * 這個方法是關鍵部分 
  35.      */  
  36.     public final void add()  
  37.     {  
  38.         try  
  39.         {  
  40.             // 實際上就是調用MyInvocationHandler的public Object invoke(Object proxy, Method method, Object[] args)方法,第二個問題就解決了  
  41.             super.h.invoke(this, m3, null);  
  42.             return;  
  43.         }  
  44.         catch(Error _ex) { }  
  45.         catch(Throwable throwable)  
  46.         {  
  47.             throw new UndeclaredThrowableException(throwable);  
  48.         }  
  49.     }  
  50.   
  51.     public final int hashCode()  
  52.     {  
  53.         try  
  54.         {  
  55.             return ((Integer)super.h.invoke(this, m0, null)).intValue();  
  56.         }  
  57.         catch(Error _ex) { }  
  58.         catch(Throwable throwable)  
  59.         {  
  60.             throw new UndeclaredThrowableException(throwable);  
  61.         }  
  62.     }  
  63.   
  64.     public final String toString()  
  65.     {  
  66.         try  
  67.         {  
  68.             return (String)super.h.invoke(this, m2, null);  
  69.         }  
  70.         catch(Error _ex) { }  
  71.         catch(Throwable throwable)  
  72.         {  
  73.             throw new UndeclaredThrowableException(throwable);  
  74.         }  
  75.     }  
  76.   
  77.     private static Method m1;  
  78.     private static Method m3;  
  79.     private static Method m0;  
  80.     private static Method m2;  
  81.   
  82.     // 在靜態代碼塊中獲取了4個方法:Object中的equals方法、UserService中的add方法、Object中的hashCode方法、Object中toString方法  
  83.     static   
  84.     {  
  85.         try  
  86.         {  
  87.             m1 = Class.forName("java.lang.Object").getMethod("equals"new Class[] {  
  88.                 Class.forName("java.lang.Object")  
  89.             });  
  90.             m3 = Class.forName("dynamic.proxy.UserService").getMethod("add"new Class[0]);  
  91.             m0 = Class.forName("java.lang.Object").getMethod("hashCode"new Class[0]);  
  92.             m2 = Class.forName("java.lang.Object").getMethod("toString"new Class[0]);  
  93.         }  
  94.         catch(NoSuchMethodException nosuchmethodexception)  
  95.         {  
  96.             throw new NoSuchMethodError(nosuchmethodexception.getMessage());  
  97.         }  
  98.         catch(ClassNotFoundException classnotfoundexception)  
  99.         {  
  100.             throw new NoClassDefFoundError(classnotfoundexception.getMessage());  
  101.         }  
  102.     }  
  103. }  


好了,到目前爲止,前面 的兩個問題都已經知道回事了,現在再用JDK動態代理的時候就不只會用而已了,真正的達到了“知其然,知其所以然”的目的。。。   

就寫到這了,累死了。。  

原文鏈接:http://rejoy.iteye.com/blog/1627405


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章