java.lang.reflect.Proxy

來源:互聯網
上載者:User

package java.lang.reflect;

import java.lang.ref.*;
import java.util.*;

import sun.misc.ProxyGenerator;

/**
 * 使用proxy的例子
 *
interface tt {
 String getSt();
}

class stt implements tt {
 public String getSt() {
  return "lqtest";
 }
}

class MyHandler implements InvocationHandler {
 tt obj;
 
 public MyHandler(tt obj) {
  this.obj = obj;
 }
 
 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  System.out.println("this is my test");
  return method.invoke(obj, args);
 }
}

  stt t = new stt();
  MyHandler hd = new MyHandler(t);
  
  tt k = (tt) Proxy.newProxyInstance(tt.class.getClassLoader(), new Class[] {tt.class}, hd);  
  String rtSt = k.getSt();
  
  Class proxyClazz = Proxy.getProxyClass(tt.class.getClassLoader(), new Class[] {tt.class});
  tt k2 = (tt) proxyClazz.getConstructor(new Class[] {InvocationHandler.class}).newInstance(new Object[] {hd});
  String rrSt2 = k2.getSt();
 * 這兩種方式都會在控制台列印出字串 
 * 代理會動態產生類proxyClazz,雖然我們裝載類常常裝載的是一個*.Class檔案但實際上
 * 符合Class檔案格式的byte數組也可以被ClassLoader裝載,如果我們熟悉Class檔案的格式,
 * 我們可以使用編程的方式動態產生類,而不局限只產生簡單的代理類,這種能力sun並沒有實現
 *
 * 代理類這種技巧常被使用在Aop技術中 
 *
 * comment by liqiang
 *
 * @author Peter Jones
 *
 */
public class Proxy implements java.io.Serializable {

    //proxy類的首碼
    private final static String proxyClassNamePrefix = "$Proxy";

    //建構函式的參數類型
    private final static Class[] constructorParams =
 { InvocationHandler.class };

    //ClassLoader與proxy類緩衝對應的緩衝
    private static Map loaderToCache = new WeakHashMap(3);

    //對應的Proxy類正在被建立的標誌
    private static Object pendingGenerationMarker = new Object();

    //用來建立唯一的Proxy類名
    private static long nextUniqueNumber = 0;
    //為建立唯一類名使用的鎖
    private static Object nextUniqueNumberLock = new Object();

    //存放所有建立的proxy類對象
    private static Map proxyClasses =
 Collections.synchronizedMap(new WeakHashMap(3));

    /**
     * the invocation handler for this proxy instance.
     * @serial
     */
    protected InvocationHandler h;

    /**
     * Prohibits instantiation.
     */
    private Proxy() {
    }

    //以InvocationHandler對象做為參數的建構函式
    protected Proxy(InvocationHandler h) {
 this.h = h;
    }

    /**
     *
     * 動態產生proxy類
     * 它有以下限制
     * 1介面數組中的每個元素應代表介面,不能表示類,或原始類型
     * 2不能出現重複的類型
     * 3Class.forName(i.getName(), false, cl) == i 成立表示介面可以
     * 通過名稱訪問到
     * 4兩個介面不能存在方法名與參數列表相同但傳回值不同的情況
     * 5介面的最大數為65535
     * 如果有以上情況則拋出IllegalArgumentException
     * 如果數組中有null的元素則拋出NullPointerException
     * 介面的順序不同會產生不同的proxy Class
     *
     *
     * @param loader 裝載這個proxy類的ClassLoader
     * @param interfaces 介面列表
     *
     */
    public static Class getProxyClass(ClassLoader loader,
          Class[] interfaces)
 throws IllegalArgumentException
    {
    //存放動態產生的類對象
 Class proxyClass = null;

 //產生proxy緩衝的索引值的StringBuffer
 StringBuffer keyBuffer = new StringBuffer();

 for (int i = 0; i < interfaces.length; i++) {
     Class interfaceClass = null;
    
     try {
     //判斷是否通過名稱可以取得介面類對象
  interfaceClass =
      Class.forName(interfaces[i].getName(), false, loader);
     } catch (ClassNotFoundException e) {
     }
    
     //如果不能通過名稱取得介面類對象則拋出異常,這時interfaceClass為null
     if (interfaceClass != interfaces[i]) {
  throw new IllegalArgumentException(
      interfaces[i] + " is not visible from class loader");
     }

     //如果介面數組中的元素不是介面則拋出異常
     if (!interfaceClass.isInterface()) {
  throw new IllegalArgumentException(
      interfaceClass.getName() + " is not an interface");
     }

     //用";"串連介面名,產生緩衝的鍵
     keyBuffer.append(interfaces[i].getName()).append(';');
 }

 //產生String的緩衝索引值,這樣別使用集合效率高
 String key = keyBuffer.toString();

 /*
  * Find or create the proxy class cache for the class loader.
  */
 Map cache;
 synchronized (loaderToCache) {
  //取得相應ClassLoader對象對象的proxy類緩衝
     cache = (Map) loaderToCache.get(loader);
    
     if (cache == null) {
     //如果沒有與此ClassLoader對應的緩衝則建立它
  cache = new HashMap(3);
  loaderToCache.put(loader, cache);
     }
    
     //在此方法的後續部分loaderToCache依然有效,但不對它做同步是因為
     //只在loader不可觸及時mapping才被移除
 }

 //通過String的索引值尋找Proxy類,會有三種情況:
 //1如果當前緩衝總沒有此Proxy類則返回null
 //2如果Proxy類正在建立則返回pendingGenerationMarker對象
 //3如果此Proxy類已經被建立,則返回WeakReference對象
 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 {
     //通過介面列表索引值取出封裝Proxy類對象的Reference對象
  Object value = cache.get(key);
  if (value instanceof Reference) {
   //從reference對象中取出proxy類對象
      proxyClass = (Class) ((Reference) value).get();
  }
  
  if (proxyClass != null) {
      //如果Proxy類對象已經建立則直接返回
      return proxyClass;
  } else if (value == pendingGenerationMarker) {
      //如果Proxy對象正在被建立則等待
      try {
   cache.wait();
      } catch (InterruptedException e) {
      //建立Class的過程很短,且為定長時間,所以這裡忽略了中斷處理
      }
     
      //Proxy被建立,或被中斷,則繼續通過索引值取緩衝中的Proxy類對象
      continue;
  } else {
      //如果沒有建立則標誌它正在建立
      cache.put(key, pendingGenerationMarker);
      //跳出迴圈,建立此Proxy類
      break;
  }
     } while (true);
 }

 try {
  //Proxy類的包
     String proxyPkg = null;

     /*
      * 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('.');
      //取得包名,如果沒有包名則使用Null 字元串表示
      String pkg = ((n == -1) ? "" : name.substring(0, n + 1));
     
      if (proxyPkg == null) {//第一個介面       
   proxyPkg = pkg;
      } else if (!pkg.equals(proxyPkg)) {
      //介面不為public且有不在同一個包下則拋出異常
   throw new IllegalArgumentException(
       "non-public interfaces from different packages");
      }
  }
  
     }

     if (proxyPkg == null) {//如果沒有非public的介面
  proxyPkg = "";  //使用匿名包
     }

     //使用了一個塊
     {
  /*
   * Choose a name for the proxy class to generate.
   */
  long num;
  synchronized (nextUniqueNumberLock) {
   //這裡使用靜態屬性作為鎖,保護了同步地區內的資料
   //因為num是long型的,無法對原始對象加鎖(只能對類加鎖)
   //而如果對整個當前對象加鎖會浪費效能
   //使用一個鎖對象,還可達到同時保護多個資料(對象,原始類型)的效果

      num = nextUniqueNumber++;
  }
  
  //拼出新的類名,類名的拼法是包名+$Proxy+唯一的long型值
  String proxyName = proxyPkg + proxyClassNamePrefix + num;
  
  //產生Class類的位元組碼
  byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
      proxyName, interfaces);
  
  try {
   //裝載此類
      proxyClass = defineClass0(loader, proxyName,
   proxyClassFile, 0, proxyClassFile.length);
  } catch (ClassFormatError e) {
      throw new IllegalArgumentException(e.toString());
  }
     }
    
     //將新建立的類對象放到存放已建立過的Proxy類的類對象的set
     proxyClasses.put(proxyClass, null);

 } finally {
     synchronized (cache) {
  if (proxyClass != null) {
   //如果建立成功則重設緩衝中的值,原來是pendingGenerationMarker
      cache.put(key, new WeakReference(proxyClass));
  } else {
   //建立不成功,則刪除掉此鍵對應項
      cache.remove(key);
  }
  
  //喚醒全部因為碰到Proxy類正在建立狀態而掛起的進程
  cache.notifyAll();
     }
 }
 
 return proxyClass;
    }

    /**
     * 建立一個Proxy Object的快速方法
     *
     * @param loader 裝載此Proxy類的ClassLoader
     * @param interfaces 介面列表
     * @param   h InvocationHandler對象
     *
     */
    public static Object newProxyInstance(ClassLoader loader,
       Class[] interfaces,
       InvocationHandler h)
 throws IllegalArgumentException
    {
 if (h == null) {
  //如果InvocationHandler為null則拋出異常
     throw new NullPointerException();
 }

 //得到Proxy類
 Class cl = getProxyClass(loader, interfaces);

 try {
  //獲得有一個InvocationHandler對象參數的建構函式
     Constructor cons = cl.getConstructor(constructorParams);
     //建立執行個體
     return (Object) cons.newInstance(new Object[] { h });
 } catch (NoSuchMethodException e) {
     throw new InternalError(e.toString());
 } catch (IllegalAccessException e) {
     throw new InternalError(e.toString());
 } catch (InstantiationException e) {
     throw new InternalError(e.toString());
 } catch (InvocationTargetException e) {
     throw new InternalError(e.toString());
 }
    }

    //判斷指定Class類是否被建立
    public static boolean isProxyClass(Class cl) {
 if (cl == null) {
     throw new NullPointerException();
 }

 return proxyClasses.containsKey(cl);
    }

    //如果proxy是Proxy對象則獲得其getInvocationHandler對象,否則拋出異常
    public static InvocationHandler getInvocationHandler(Object proxy)
 throws IllegalArgumentException
    {
 //檢測proxy對象是否是已經產生的Proxy類的對象
 if (!isProxyClass(proxy.getClass())) {
     throw new IllegalArgumentException("not a proxy instance");
 }

 //如果是則轉型
 Proxy p = (Proxy) proxy;
 return p.h;
    }

    //載入類的本地方法
    private static native Class defineClass0(ClassLoader loader, String name,
          byte[] b, int off, int len);
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.