最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java動(dòng)態(tài)代理分析及理解

 更新時(shí)間:2017年05月10日 11:23:28   作者:Java開(kāi)發(fā)-10  
這篇文章主要介紹了Java動(dòng)態(tài)代理分析及理解的相關(guān)資料,需要的朋友可以參考下

Java動(dòng)態(tài)代理分析及理解

代理設(shè)計(jì)模式

定義:為其他對(duì)象提供一種代理以控制對(duì)這個(gè)對(duì)象的訪問(wèn)。

動(dòng)態(tài)代理使用

java動(dòng)態(tài)代理機(jī)制以巧妙的方式實(shí)現(xiàn)了代理模式的設(shè)計(jì)理念。

代理模式示例代碼

public interface Subject  
{  
 public void doSomething();  
}  
public class RealSubject implements Subject  
{  
 public void doSomething()  
 {  
  System.out.println( "call doSomething()" );  
 }  
}  
public class ProxyHandler implements InvocationHandler  
{  
 private Object proxied;  
   
 public ProxyHandler( Object proxied )  
 {  
  this.proxied = proxied;  
 }  
   
 public Object invoke( Object proxy, Method method, Object[] args ) throws Throwable  
 {  
  //在轉(zhuǎn)調(diào)具體目標(biāo)對(duì)象之前,可以執(zhí)行一些功能處理

  //轉(zhuǎn)調(diào)具體目標(biāo)對(duì)象的方法
  return method.invoke( proxied, args); 
  
  //在轉(zhuǎn)調(diào)具體目標(biāo)對(duì)象之后,可以執(zhí)行一些功能處理
 }  
} 
import java.lang.reflect.InvocationHandler;  
import java.lang.reflect.Method;  
import java.lang.reflect.Proxy;  
import sun.misc.ProxyGenerator;  
import java.io.*;  
public class DynamicProxy  
{  
 public static void main( String args[] )  
 {  
  RealSubject real = new RealSubject();  
  Subject proxySubject = (Subject)Proxy.newProxyInstance(Subject.class.getClassLoader(), 
   new Class[]{Subject.class}, 
   new ProxyHandler(real));
     
  proxySubject.doSomething();
  
  //write proxySubject class binary data to file  
  createProxyClassFile();  
 }  
   
 public static void createProxyClassFile()  
 {  
  String name = "ProxySubject";  
  byte[] data = ProxyGenerator.generateProxyClass( name, new Class[] { Subject.class } );  
  try 
  {  
   FileOutputStream out = new FileOutputStream( name + ".class" );  
   out.write( data );  
   out.close();  
  }  
  catch( Exception e )  
  {  
   e.printStackTrace();  
  }  
 }  
} 

動(dòng)態(tài)代理內(nèi)部實(shí)現(xiàn)

首先來(lái)看看類Proxy的代碼實(shí)現(xiàn) Proxy的主要靜態(tài)變量

// 映射表:用于維護(hù)類裝載器對(duì)象到其對(duì)應(yīng)的代理類緩存
private static Map loaderToCache = new WeakHashMap(); 

// 標(biāo)記:用于標(biāo)記一個(gè)動(dòng)態(tài)代理類正在被創(chuàng)建中
private static Object pendingGenerationMarker = new Object(); 

// 同步表:記錄已經(jīng)被創(chuàng)建的動(dòng)態(tài)代理類類型,主要被方法 isProxyClass 進(jìn)行相關(guān)的判斷
private static Map proxyClasses = Collections.synchronizedMap(new WeakHashMap()); 

// 關(guān)聯(lián)的調(diào)用處理器引用
protected InvocationHandler h;

Proxy的構(gòu)造方法

// 由于 Proxy 內(nèi)部從不直接調(diào)用構(gòu)造函數(shù),所以 private 類型意味著禁止任何調(diào)用
private Proxy() {} 

// 由于 Proxy 內(nèi)部從不直接調(diào)用構(gòu)造函數(shù),所以 protected 意味著只有子類可以調(diào)用
protected Proxy(InvocationHandler h) {this.h = h;} 

Proxy靜態(tài)方法newProxyInstance

public static Object newProxyInstance(ClassLoader loader, Class<?>[]interfaces,InvocationHandler h) throws IllegalArgumentException { 
  // 檢查 h 不為空,否則拋異常
  if (h == null) { 
    throw new NullPointerException(); 
  } 

  // 獲得與指定類裝載器和一組接口相關(guān)的代理類類型對(duì)象
  Class cl = getProxyClass(loader, interfaces); 

  // 通過(guò)反射獲取構(gòu)造函數(shù)對(duì)象并生成代理類實(shí)例
  try { 
    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()); 
  } 
}

類Proxy的getProxyClass方法調(diào)用ProxyGenerator的 generateProxyClass方法產(chǎn)生ProxySubject.class的二進(jìn)制數(shù)據(jù):

public static byte[] generateProxyClass(final String name, Class[] interfaces)

我們可以import sun.misc.ProxyGenerator,調(diào)用 generateProxyClass方法產(chǎn)生binary data,然后寫入文件,最后通過(guò)反編譯工具來(lái)查看內(nèi)部實(shí)現(xiàn)原理。 反編譯后的ProxySubject.java Proxy靜態(tài)方法newProxyInstance

import java.lang.reflect.*;  
public final class ProxySubject extends Proxy  
  implements Subject  
{  
  private static Method m1;  
  private static Method m0;  
  private static Method m3;  
  private static Method m2;  
  public ProxySubject(InvocationHandler invocationhandler)  
  {  
    super(invocationhandler);  
  }  
  public final boolean equals(Object obj)  
  {  
    try 
    {  
      return ((Boolean)super.h.invoke(this, m1, new Object[] {  
        obj  
      })).booleanValue();  
    }  
    catch(Error _ex) { }  
    catch(Throwable throwable)  
    {  
      throw new UndeclaredThrowableException(throwable);  
    }  
  }  
  public final int hashCode()  
  {  
    try 
    {  
      return ((Integer)super.h.invoke(this, m0, null)).intValue();  
    }  
    catch(Error _ex) { }  
    catch(Throwable throwable)  
    {  
      throw new UndeclaredThrowableException(throwable);  
    }  
  }  
  public final void doSomething()  
  {  
    try 
    {  
      super.h.invoke(this, m3, null);  
      return;  
    }  
    catch(Error _ex) { }  
    catch(Throwable throwable)  
    {  
      throw new UndeclaredThrowableException(throwable);  
    }  
  }  
  public final String toString()  
  {  
    try 
    {  
      return (String)super.h.invoke(this, m2, null);  
    }  
    catch(Error _ex) { }  
    catch(Throwable throwable)  
    {  
      throw new UndeclaredThrowableException(throwable);  
    }  
  }  
  static  
  {  
    try 
    {  
      m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[] {  
        Class.forName("java.lang.Object")  
      });  
      m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);  
      m3 = Class.forName("Subject").getMethod("doSomething", new Class[0]);  
      m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);  
    }  
    catch(NoSuchMethodException nosuchmethodexception)  
    {  
      throw new NoSuchMethodError(nosuchmethodexception.getMessage());  
    }  
    catch(ClassNotFoundException classnotfoundexception)  
    {  
      throw new NoClassDefFoundError(classnotfoundexception.getMessage());  
    }  
  }  
} 

ProxyGenerator內(nèi)部是如何生成class二進(jìn)制數(shù)據(jù),可以參考源代碼。

private byte[] generateClassFile() {  
 /* 
  * Record that proxy methods are needed for the hashCode, equals, 
  * and toString methods of java.lang.Object. This is done before 
  * the methods from the proxy interfaces so that the methods from 
  * java.lang.Object take precedence over duplicate methods in the 
  * proxy interfaces. 
  */ 
 addProxyMethod(hashCodeMethod, Object.class);  
 addProxyMethod(equalsMethod, Object.class);  
 addProxyMethod(toStringMethod, Object.class);  
 /* 
  * Now record all of the methods from the proxy interfaces, giving 
  * earlier interfaces precedence over later ones with duplicate 
  * methods. 
  */ 
 for (int i = 0; i < interfaces.length; i++) {  
   Method[] methods = interfaces[i].getMethods();  
   for (int j = 0; j < methods.length; j++) {  
  addProxyMethod(methods[j], interfaces[i]);  
   }  
 }  
 /* 
  * For each set of proxy methods with the same signature, 
  * verify that the methods' return types are compatible. 
  */ 
 for (List<ProxyMethod> sigmethods : proxyMethods.values()) {  
   checkReturnTypes(sigmethods);  
 }  
 /* ============================================================ 
  * Step 2: Assemble FieldInfo and MethodInfo structs for all of 
  * fields and methods in the class we are generating. 
  */ 
 try {  
   methods.add(generateConstructor());  
   for (List<ProxyMethod> sigmethods : proxyMethods.values()) {  
  for (ProxyMethod pm : sigmethods) {  
    // add static field for method's Method object  
    fields.add(new FieldInfo(pm.methodFieldName,  
   "Ljava/lang/reflect/Method;",  
    ACC_PRIVATE | ACC_STATIC));  
    // generate code for proxy method and add it  
    methods.add(pm.generateMethod());  
  }  
   }  
   methods.add(generateStaticInitializer());  
 } catch (IOException e) {  
   throw new InternalError("unexpected I/O Exception");  
 }  
 /* ============================================================ 
  * Step 3: Write the final class file. 
  */ 
 /* 
  * Make sure that constant pool indexes are reserved for the 
  * following items before starting to write the final class file. 
  */ 
 cp.getClass(dotToSlash(className));  
 cp.getClass(superclassName);  
 for (int i = 0; i < interfaces.length; i++) {  
   cp.getClass(dotToSlash(interfaces[i].getName()));  
 }  
 /* 
  * Disallow new constant pool additions beyond this point, since 
  * we are about to write the final constant pool table. 
  */ 
 cp.setReadOnly();  
 ByteArrayOutputStream bout = new ByteArrayOutputStream();  
 DataOutputStream dout = new DataOutputStream(bout);  
 try {  
   /* 
    * Write all the items of the "ClassFile" structure. 
    * See JVMS section 4.1. 
    */ 
     // u4 magic;  
   dout.writeInt(0xCAFEBABE);  
     // u2 minor_version;  
   dout.writeShort(CLASSFILE_MINOR_VERSION);  
     // u2 major_version;  
   dout.writeShort(CLASSFILE_MAJOR_VERSION);  
   cp.write(dout);  // (write constant pool)  
     // u2 access_flags;  
   dout.writeShort(ACC_PUBLIC | ACC_FINAL | ACC_SUPER);  
     // u2 this_class;  
   dout.writeShort(cp.getClass(dotToSlash(className)));  
     // u2 super_class;  
   dout.writeShort(cp.getClass(superclassName));  
     // u2 interfaces_count;  
   dout.writeShort(interfaces.length);  
     // u2 interfaces[interfaces_count];  
   for (int i = 0; i < interfaces.length; i++) {  
  dout.writeShort(cp.getClass(  
    dotToSlash(interfaces[i].getName())));  
   }  
     // u2 fields_count;  
   dout.writeShort(fields.size());  
     // field_info fields[fields_count];  
   for (FieldInfo f : fields) {  
  f.write(dout);  
   }  
     // u2 methods_count;  
   dout.writeShort(methods.size());  
     // method_info methods[methods_count];  
   for (MethodInfo m : methods) {  
  m.write(dout);  
   }  
       // u2 attributes_count;  
   dout.writeShort(0); // (no ClassFile attributes for proxy classes)  
 } catch (IOException e) {  
   throw new InternalError("unexpected I/O Exception");  
 }  
 return bout.toByteArray(); 

總結(jié)

一個(gè)典型的動(dòng)態(tài)代理創(chuàng)建對(duì)象過(guò)程可分為以下四個(gè)步驟:

1、通過(guò)實(shí)現(xiàn)InvocationHandler接口創(chuàng)建自己的調(diào)用處理器 IvocationHandler handler = new InvocationHandlerImpl(...);
2、通過(guò)為Proxy類指定ClassLoader對(duì)象和一組interface創(chuàng)建動(dòng)態(tài)代理類
Class clazz = Proxy.getProxyClass(classLoader,new Class[]{...});
3、通過(guò)反射機(jī)制獲取動(dòng)態(tài)代理類的構(gòu)造函數(shù),其參數(shù)類型是調(diào)用處理器接口類型
Constructor constructor = clazz.getConstructor(new Class[]{InvocationHandler.class});
4、通過(guò)構(gòu)造函數(shù)創(chuàng)建代理類實(shí)例,此時(shí)需將調(diào)用處理器對(duì)象作為參數(shù)被傳入
Interface Proxy = (Interface)constructor.newInstance(new Object[] (handler));
為了簡(jiǎn)化對(duì)象創(chuàng)建過(guò)程,Proxy類中的newInstance方法封裝了2~4,只需兩步即可完成代理對(duì)象的創(chuàng)建。
生成的ProxySubject繼承Proxy類實(shí)現(xiàn)Subject接口,實(shí)現(xiàn)的Subject的方法實(shí)際調(diào)用處理器的invoke方法,而invoke方法利用反射調(diào)用的是被代理對(duì)象的的方法(Object result=method.invoke(proxied,args))

美中不足

誠(chéng)然,Proxy已經(jīng)設(shè)計(jì)得非常優(yōu)美,但是還是有一點(diǎn)點(diǎn)小小的遺憾之處,那就是它始終無(wú)法擺脫僅支持interface代理的桎梏,因?yàn)樗脑O(shè)計(jì)注定了這個(gè)遺憾。回想一下那些動(dòng)態(tài)生成的代理類的繼承關(guān)系圖,它們已經(jīng)注定有一個(gè)共同的父類叫Proxy。Java的繼承機(jī)制注定了這些動(dòng)態(tài)代理類們無(wú)法實(shí)現(xiàn)對(duì)class的動(dòng)態(tài)代理,原因是多繼承在Java中本質(zhì)上就行不通。有很多條理由,人們可以否定對(duì) class代理的必要性,但是同樣有一些理由,相信支持class動(dòng)態(tài)代理會(huì)更美好。接口和類的劃分,本就不是很明顯,只是到了Java中才變得如此的細(xì)化。如果只從方法的聲明及是否被定義來(lái)考量,有一種兩者的混合體,它的名字叫抽象類。實(shí)現(xiàn)對(duì)抽象類的動(dòng)態(tài)代理,相信也有其內(nèi)在的價(jià)值。此外,還有一些歷史遺留的類,它們將因?yàn)闆](méi)有實(shí)現(xiàn)任何接口而從此與動(dòng)態(tài)代理永世無(wú)緣。如此種種,不得不說(shuō)是一個(gè)小小的遺憾。但是,不完美并不等于不偉大,偉大是一種本質(zhì),Java動(dòng)態(tài)代理就是佐例。

感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!

相關(guān)文章

  • springboot實(shí)現(xiàn)配置本地訪問(wèn)端口及路徑

    springboot實(shí)現(xiàn)配置本地訪問(wèn)端口及路徑

    這篇文章主要介紹了springboot實(shí)現(xiàn)配置本地訪問(wèn)端口及路徑,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-01-01
  • java調(diào)用淘寶api聯(lián)網(wǎng)查詢ip歸屬地

    java調(diào)用淘寶api聯(lián)網(wǎng)查詢ip歸屬地

    java聯(lián)網(wǎng)查詢IP歸屬地,原理是根據(jù)淘寶提供的service查詢IP的歸屬地并且解析http請(qǐng)求返回的json串
    2014-03-03
  • Maven pom.xml scope屬性的使用

    Maven pom.xml scope屬性的使用

    在Maven中,scope屬性用于定義依賴關(guān)系在不同生命周期階段的行為,影響依賴在構(gòu)建過(guò)程中的下載和使用,以及是否傳遞給其他項(xiàng)目,常見(jiàn)的scope值包括compile、provided、runtime和test等
    2025-01-01
  • java讀取文件顯示進(jìn)度條的實(shí)現(xiàn)方法

    java讀取文件顯示進(jìn)度條的實(shí)現(xiàn)方法

    當(dāng)讀取一個(gè)大文件時(shí),一時(shí)半會(huì)兒無(wú)法看到讀取結(jié)果,就需要顯示一個(gè)進(jìn)度條,是程序員明白已經(jīng)讀了多少文件,可以估算讀取還需要多少時(shí)間,下面的代碼可以實(shí)現(xiàn)這個(gè)功能
    2014-01-01
  • Spring MVC文件配置以及參數(shù)傳遞示例詳解

    Spring MVC文件配置以及參數(shù)傳遞示例詳解

    這篇文章主要給大家介紹了關(guān)于Spring MVC文件配置以及參數(shù)傳遞的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2021-03-03
  • response.setContentType()參數(shù)以及作用詳解

    response.setContentType()參數(shù)以及作用詳解

    這篇文章主要介紹了response.setContentType()參數(shù)以及作用詳解,本篇文章通過(guò)簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下
    2021-08-08
  • VsCode配置java環(huán)境的詳細(xì)圖文教程

    VsCode配置java環(huán)境的詳細(xì)圖文教程

    vscode是一個(gè)免費(fèi)的代碼編輯器,支持多種主題,應(yīng)用起來(lái)簡(jiǎn)單方便,下面這篇文章主要給大家介紹了關(guān)于VsCode配置java環(huán)境的詳細(xì)圖文教程,文中通過(guò)圖文介紹的非常詳細(xì),需要的朋友可以參考下
    2023-02-02
  • Mybatis-Plus可能導(dǎo)致死鎖的問(wèn)題分析及解決辦法

    Mybatis-Plus可能導(dǎo)致死鎖的問(wèn)題分析及解決辦法

    這篇文章給大家主要介紹了Mybatis-Plus可能導(dǎo)致死鎖的問(wèn)題分析及解決辦法,文中通過(guò)代碼示例給大家介紹的非常詳細(xì),具有一定的參考價(jià)值,需要的朋友可以參考下
    2023-12-12
  • springboot中redis的緩存穿透問(wèn)題實(shí)現(xiàn)

    springboot中redis的緩存穿透問(wèn)題實(shí)現(xiàn)

    這篇文章主要介紹了springboot中redis的緩存穿透問(wèn)題實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2021-02-02
  • Springboot項(xiàng)目實(shí)現(xiàn)Mysql多數(shù)據(jù)源切換的完整實(shí)例

    Springboot項(xiàng)目實(shí)現(xiàn)Mysql多數(shù)據(jù)源切換的完整實(shí)例

    這篇文章主要給大家介紹了關(guān)于Springboot項(xiàng)目實(shí)現(xiàn)Mysql多數(shù)據(jù)源切換的完整實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-11-11

最新評(píng)論

青田县| 崇州市| 洮南市| 班戈县| 五华县| 乌鲁木齐县| 嘉荫县| 通山县| 疏附县| 元氏县| 收藏| 孝昌县| 宣汉县| 廊坊市| 陈巴尔虎旗| 剑阁县| 宁明县| 达日县| 积石山| 师宗县| 洛川县| 江油市| 绥棱县| 彰化县| 宜良县| 河池市| 修武县| 秀山| 南溪县| 夏津县| 江达县| 来安县| 温宿县| 宿松县| 永兴县| 沭阳县| 南江县| 沧源| 资溪县| 东源县| 洛隆县|