動態代理及JDK動態代理源碼分析

1.爲什麼要動態代理
現在有這樣一個需求:在聊天系統中,把每一個所說的話記錄到日誌文件裏面,初學者可能是這樣來設計


在speak方法中調用log方法,記錄到數據庫。這樣設計有明顯的不足:1、log方法不應該屬於Person類中 2、如果改類庫已經編譯,我們就不能修改原有代碼,在其方法內部增加代碼。此時,有經驗的開發者可能會想到代理模式。我們修改一下類圖


我們將講話給抽象出來,客戶端使用接口聲明,LogProxy與Person依賴,共同實現Speak接口,然後在LogPersonProxy中實現記錄日誌,這樣就可以解決之前的問題。但是新問題又來了:我們必須爲爲委託類維護一個代理,不易管理而且增加了代碼量。


2.JDK中的動態代理
JAVA的動態代理機制可以動態的創建代理並動態的處理代理方法調用,只要簡單指定一組接口及爲拖累對象,就能動態的獲取代理類,JAVA已經給我們提供了強大的支持,其具體實現可以參照馬士兵的動態代理視頻。核心類是Proxy,負責創建所有代理類,並且創建的代理類都是其子類,而且這些子類繼承所代理的一組接口,因此它就可以安全的轉換成需要的類型,進行方法調用。InvocationHandler是調用處理器的接口,它自定義了一個invoke方法,用於機制處理在動態代理類上的方法調用,通常在該方法中實現對委託類的代理訪問。相關類圖如下



具體代理要實現InvocationHandler接口詳細代碼如下

public class LogProxy implements InvocationHandler {
 
 private Object object;
 public LogProxy(Object object) {
  super();
  this.object = object;
 }
 @Override
 public Object invoke(Object proxy, Method method, Object[] args)
   throws Throwable {
  method.invoke(this.object, args);
  System.out.println("記錄到數據庫..");
  return null;
 }
 public void setObject(Object object) {
  this.object = object;
 }
 public Object getObject() {
  return object;
 }
}
public class PowerProxy implements InvocationHandler {
 private Object object;
 public PowerProxy(Object object) {
  super();
  this.object = object;
 }
 
 @Override
 public Object invoke(Object proxy, Method method, Object[] args)
   throws Throwable {
  System.out.println("進行權限驗證..是否是黑名單..");
  method.invoke(this.object, args);
  return null;
 }
 public void setObject(Object object) {
  this.object = object;
 }
 public Object getObject() {
  return object;
 }
}




我們可以在invoke方法中接到一下參數:Object proxy, Method method, Object[] args


其中,proxy是被代理的類,第二個參數表示被執行的委託方法,第三個參數表被執行的委託方法,我們在客戶端測試一下,代碼如下
public class Client {
 /**
  * @Title: main
  * @Description: TODO(這裏用一句話描述這個方法的作用)
  * @param args 描述
  * @return void 返回類型
  * @throws
  */
 public static void main(String[] args) {
  Person zhangsan = new Person("張三");
  Zegapain jiqiren = new Zegapain("編號89757");
  Speakable zhangsanProxy = (Speakable) Proxy.newProxyInstance(Speakable.class.getClassLoader(), new Class[]{Speakable.class}, new LogProxy(zhangsan));
  Speakable jiqirenProxy = (Speakable) Proxy.newProxyInstance(Speakable.class.getClassLoader(), new Class[]{Speakable.class}, new LogProxy(jiqiren));
  zhangsanProxy.speak("呵呵");
  jiqirenProxy.speak("您好,我是機器人");
  System.out.println("----------------------------");
  Speakable zhangsanPowerProxy = (Speakable) Proxy.newProxyInstance(Speakable.class.getClassLoader(), new Class[]{Speakable.class}, new PowerProxy(zhangsan));
  zhangsanPowerProxy.speak("我不是壞人");
  System.out.println("----------------------------");
    Speakable jiqirenPowerProxy = (Speakable) Proxy.newProxyInstance(Speakable.class.getClassLoader(), new Class[]{Speakable.class}, new PowerProxy(jiqirenProxy));
    jiqirenPowerProxy.speak("我是您的機器人");
 }
}




3.JDK動態代理必須要接口的原因


在aspectj和cglib裏面,被代理的對象要實現一個接口如上面的測試代碼:

 Speakable zhangsanPowerProxy = (Speakable) Proxy.newProxyInstance(Speakable.class.getClassLoader(), new Class[]{Speakable.class}, new PowerProxy(zhangsan)); 


 
在cglib下是這樣的:

TestProxy tp = new TestProxy();
zhangsan= (Person ) tp.getProxy(Person.class);



JDK動態代理爲什麼必須使用接口?這個問題很有意思。
我們查看Proxy的源碼


Class cl = getProxyClass(loader, interfaces);


上面代碼是創建一個代理類,我們看看getProxyClass的源碼

 if (interfaces.length > 65535) {
     throw new IllegalArgumentException("interface limit exceeded");
 }


接口類數組的長度小於65535,65535是計算機16位二進制最大數,如果大於就會內存溢出,繼續往下。
Class proxyClass = null;
 /* collect interface names to use as key for proxy class cache */
 String[] interfaceNames = new String[interfaces.length];
 Set interfaceSet = new HashSet();	// for detecting duplicates
 for (int i = 0; i < interfaces.length; i++) {
     /*
      * Verify that the class loader resolves the name of this
      * interface to the same Class object.
      */
     String interfaceName = interfaces[i].getName();
     Class interfaceClass = null;
     try {
  interfaceClass = Class.forName(interfaceName, false, loader);
     } catch (ClassNotFoundException e) {
     }
     if (interfaceClass != interfaces[i]) {
  throw new IllegalArgumentException(
      interfaces[i] + " 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.contains(interfaceClass)) {
  throw new IllegalArgumentException(
      "repeated interface: " + interfaceClass.getName());
     }
     interfaceSet.add(interfaceClass);
     interfaceNames[i] = interfaceName;
 }



從上面代碼可以看出,接口名放在了一個數組裏,接口類的Class的數組緩存在了了HashSet裏面,之所以用Set是爲了排除重複


Map cache;
 synchronized (loaderToCache) {
     cache = (Map) loaderToCache.get(loader);
     if (cache == null) {
  cache = new HashMap();
  loaderToCache.put(loader, cache);
     }
     /*
      * This mapping will remain valid for the duration of this
      * method, without further synchronization, because the mapping
      * will only be removed if the class loader becomes unreachable.
      */
 }
 /*
  * Look up the list of interfaces in the proxy class cache using
  * the key. This lookup will result in one of three possible
  * kinds of values:
  * null, if there is currently no proxy class for the list of
  * interfaces in the class loader,
  * the pendingGenerationMarker object, if a proxy class for the
  * list of interfaces is currently being generated,
  * or a weak reference to a Class object, if a proxy class for
  * the list of interfaces has already been generated.
  */
 synchronized (cache) {
     /*
      * Note that we need not worry about reaping the cache for
      * entries with cleared weak references because if a proxy class
      * has been garbage collected, its class loader will have been
      * garbage collected as well, so the entire cache will be reaped
      * from the loaderToCache map.
      */
     do {
  Object value = cache.get(key);
  if (value instanceof Reference) {
      proxyClass = (Class) ((Reference) value).get();
  }
  if (proxyClass != null) {
      // proxy class already generated: return it
      return proxyClass;
  } else if (value == pendingGenerationMarker) {
      // proxy class being generated: wait for it
      try {
   cache.wait();
      } catch (InterruptedException e) {
   /*
    * The class generation that we are waiting for should
    * take a small, bounded time, so we can safely ignore
    * thread interrupts here.
    */
      }
      continue;
  } else {
      /*
       * No proxy class for this list of interfaces has been
       * generated or is being generated, so we will go and
       * generate it now. Mark it as pending generation.
       */
      cache.put(key, pendingGenerationMarker);
      break;
  }
     } while (true);
 }



找到或創建的類加載器代理類緩存

String proxyPkg = null;
String proxyPkg = null;	// package to define proxy class in
     /*
      * 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 (int i = 0; i < interfaces.length; i++) {
  int flags = interfaces[i].getModifiers();
  if (!Modifier.isPublic(flags)) {
      String name = interfaces[i].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,
  proxyPkg = "";	 // use the unnamed package
     }

	// package to define proxy class in
     /*
      * 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 (int i = 0; i < interfaces.length; i++) {
  int flags = interfaces[i].getModifiers();
  if (!Modifier.isPublic(flags)) {
      String name = interfaces[i].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,
  proxyPkg = "";	 // use the unnamed package
     }



這句代碼是給新生成的代理類截取接口,JDK是這樣設計的:如果接口爲public,則生成到頂包底下,如果爲默認修飾符,也就是修飾符爲空,則會生成到接口所定義的包下,繼續往下


long num;
  synchronized (nextUniqueNumberLock) {
      num = nextUniqueNumber++;
  }
  String proxyName = proxyPkg + proxyClassNamePrefix + num;




這裏是設計動態代理類的類名,JDK的設計師爲"$ProxyN",其中N爲從0遞增的一個阿拉伯數字,加了synchronized 關鍵字,不會重複


byte[] proxyClassFile =	ProxyGenerator.generateProxyClass(
      proxyName, interfaces);
  try {
      proxyClass = 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());
  }
     }
     // add to set of all generated proxy classes, for isProxyClass
     proxyClasses.put(proxyClass, null);
 } finally {
     /*
      * We must clean up the "pending generation" state of the proxy
      * class cache entry somehow. If a proxy class was successfully
      * generated, store it in the cache (with a weak reference);
      * otherwise, remove the reserved entry. In all cases, notify
      * all waiters on reserved entries in this cache.
      */
     synchronized (cache) {
  if (proxyClass != null) {
      cache.put(key, new WeakReference(proxyClass));
  } else {
      cache.remove(key);
  }
  cache.notifyAll();
     }
 }
 return proxyClass;
    }




上面代碼是說調用class處理文件生成類的字節碼,根據接口列表創建一個新類,這個類爲代理類,通過JNI接口,將Class字節碼文件定義一個新類,下面是newProxyInstance後面的代碼


Constructor cons = cl.getConstructor(constructorParams);
return (Object) cons.newInstance(new Object[] { h });


根據前面的代碼Constructor cons = cl.getConstructor(constructorParams);


可以猜測到接口創建的新類proxyClassFile 不管採用什麼接口,都是以下結構


public class $Proxy1 extends Proxy implements 傳入的接口{


    


}
生成新類的看不到源代碼,不過猜測它的執行原理很有可能是如果類是Proxy的子類,則調用InvocationHandler進行方法的Invoke
到現在大家都應該明白了吧,JDK動態代理的原理是根據定義好的規則,用傳入的接口創建一個新類,JDK的動態代理只能代理接口中的方法,是針對接口生成代理類。  
這就是爲什麼採用動態代理時爲什麼只能用接口引用指向代理,而不能用傳入的類引用執行動態類。




附:Spring中的動態代理
關於Spring中的動態代理我之前寫過一篇博文《對Spring.Net的AOP一些思考及應用》,裏面寫的比較的深在裏面舉得例子有點複雜,大家在第一次看的時候可以看看一個博友的《Spring.Net 面向切面AOP》


參考:

《spring 3.x 企業級應用程序開發實戰》

http://www.cnblogs.com/frankliiu-java/articles/1896443.html




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