深入理解Proxy机制

来源:互联网 发布:淘宝女裤品牌 编辑:程序博客网 时间:2024/06/05 04:27
动态代理其实就是java.lang.reflect.Proxy类动态的根据您指定的所有接口生成一个class byte,该class会继承Proxy类,并实现所有你指定的接口(您在参数中传入的接口数组);然后再利用您指定的classloader将 class byte加载进系统,最后生成这样一个类的对象,并初始化该对象的一些值,如invocationHandler,以即所有的接口对应的Method成员。 初始化之后将对象返回给调用的客户端。这样客户端拿到的就是一个实现你所有的接口的Proxy对象。请看实例分析:

一  业务接口类

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public interface BusinessProcessor {  
  2.  public void processBusiness();  
  3. }  



二 业务实现类

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public class BusinessProcessorImpl implements BusinessProcessor {  
  2.  public void processBusiness() {  
  3.   System.out.println("processing business.....");  
  4.  }  
  5. }  



三 业务代理类

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. import java.lang.reflect.InvocationHandler;  
  2. import java.lang.reflect.Method;  
  3.   
  4. public class BusinessProcessorHandler implements InvocationHandler {  
  5.   
  6.  private Object target = null;  
  7.    
  8.  BusinessProcessorHandler(Object target){  
  9.   this.target = target;  
  10.  }  
  11.    
  12.  public Object invoke(Object proxy, Method method, Object[] args)  
  13.    throws Throwable {  
  14.   System.out.println("You can do something here before process your business");  
  15.   Object result = method.invoke(target, args);  
  16.   System.out.println("You can do something here after process your business");  
  17.   return result;  
  18.  }  
  19.   
  20. }  



四 客户端应用类

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. import java.lang.reflect.Field;  
  2. import java.lang.reflect.Method;  
  3. import java.lang.reflect.Modifier;  
  4. import java.lang.reflect.Proxy;  
  5.   
  6. public class Test {  
  7.   
  8.  public static void main(String[] args) {  
  9.   BusinessProcessorImpl bpimpl = new BusinessProcessorImpl();  
  10.   BusinessProcessorHandler handler = new BusinessProcessorHandler(bpimpl);  
  11.   BusinessProcessor bp = (BusinessProcessor)Proxy.newProxyInstance(bpimpl.getClass().getClassLoader(), bpimpl.getClass().getInterfaces(), handler);  
  12.   bp.processBusiness();  
  13.  }  
  14. }  


现在我们看一下打印结果:

You can do something here before process your business
processing business.....
You can do something here after process your business

通过结果我们就能够很简单的看出Proxy的作用了,它能够在你的核心业务方法前后做一些你所想做的辅助工作,如log日志,安全机制等等。

 

现在我们来分析一下上面的类的工作原理。

类一二没什么好说的。先看看类三吧。 实现了InvocationHandler接口的invoke方法。其实这个类就是最终Proxy调用的固定接口方法。Proxy不管客户端的业务方法是怎么实现的。当客户端调用Proxy时,它只

会调用InvocationHandler的invoke接口,所以我们的真正实现的方法就必须在invoke方法中去调用。关系如下:

 BusinessProcessorImpl bpimpl = new BusinessProcessorImpl();
 BusinessProcessorHandler handler = new BusinessProcessorHandler(bpimpl);

BusinessProcessor bp = (BusinessProcessor)Proxy.newProxyInstance(....);

bp.processBusiness()-->invocationHandler.invoke()-->bpimpl.processBusiness();

那么bp到底是怎么样一个对象呢。我们改一下main方法看一下就知道了:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public static void main(String[] args) {  
  2.  BusinessProcessorImpl bpimpl = new BusinessProcessorImpl();  
  3.  BusinessProcessorHandler handler = new BusinessProcessorHandler(bpimpl);  
  4.  BusinessProcessor bp = (BusinessProcessor)Proxy.newProxyInstance(bpimpl.getClass().getClassLoader(), bpimpl.getClass().getInterfaces(), handler);  
  5.  bp.processBusiness();  
  6.  System.out.println(bp.getClass().getName());  
  7. }  


输出结果:

You can do something here before process your business
processing business.....
You can do something here after process your business
$Proxy0

bp原来是个$Proxy0这个类的对象。那么这个类到底是长什么样子呢?好的。我们再写二个方法去把这个类打印出来看个究竟,是什么三头六臂呢?我们在main下面写如下两个静态方法。

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public static String getModifier(int modifier){  
  2.   String result = "";  
  3.   switch(modifier){  
  4.    case Modifier.PRIVATE:  
  5.     result = "private";  
  6.    case Modifier.PUBLIC:  
  7.     result = "public";  
  8.    case Modifier.PROTECTED:  
  9.     result = "protected";  
  10.    case Modifier.ABSTRACT :  
  11.     result = "abstract";  
  12.    case Modifier.FINAL :  
  13.     result = "final";  
  14.    case Modifier.NATIVE :  
  15.     result = "native";  
  16.    case Modifier.STATIC :  
  17.     result = "static";  
  18.    case Modifier.SYNCHRONIZED :  
  19.     result = "synchronized";  
  20.    case Modifier.STRICT  :  
  21.     result = "strict";  
  22.    case Modifier.TRANSIENT :  
  23.     result = "transient";  
  24.    case Modifier.VOLATILE :  
  25.     result = "volatile";  
  26.    case Modifier.INTERFACE :  
  27.     result = "interface";  
  28.   }  
  29.   return result;  
  30.  }  
  31.    
  32.  public static void printClassDefinition(Class clz){  
  33.     
  34.   String clzModifier = getModifier(clz.getModifiers());  
  35.   if(clzModifier!=null && !clzModifier.equals("")){  
  36.    clzModifier = clzModifier + " ";  
  37.   }  
  38.   String superClz = clz.getSuperclass().getName();  
  39.   if(superClz!=null && !superClz.equals("")){  
  40.    superClz = "extends " + superClz;  
  41.   }  
  42.     
  43.   Class[] interfaces = clz.getInterfaces();  
  44.     
  45.   String inters = "";  
  46.   for(int i=0; i<interfaces.length; i++){  
  47.    if(i==0){  
  48.     inters += "implements ";  
  49.    }  
  50.    inters += interfaces[i].getName();  
  51.   }  
  52.     
  53.   System.out.println(clzModifier +clz.getName()+" " + superClz +" " + inters );  
  54.   System.out.println("{");  
  55.     
  56.   Field[] fields = clz.getDeclaredFields();  
  57.   for(int i=0; i<fields.length; i++){  
  58.    String modifier = getModifier(fields[i].getModifiers());  
  59.    if(modifier!=null && !modifier.equals("")){  
  60.     modifier = modifier + " ";  
  61.    }  
  62.    String fieldName = fields[i].getName();  
  63.    String fieldType = fields[i].getType().getName();  
  64.    System.out.println("    "+modifier + fieldType + " "+ fieldName + ";");  
  65.   }  
  66.     
  67.   System.out.println();  
  68.     
  69.   Method[] methods = clz.getDeclaredMethods();  
  70.   for(int i=0; i<methods.length; i++){  
  71.    Method method = methods[i];  
  72.   
  73.    String modifier = getModifier(method.getModifiers());  
  74.    if(modifier!=null && !modifier.equals("")){  
  75.     modifier = modifier + " ";  
  76.    }  
  77.      
  78.    String methodName = method.getName();  
  79.      
  80.    Class returnClz = method.getReturnType();  
  81.    String retrunType = returnClz.getName();  
  82.      
  83.    Class[] clzs = method.getParameterTypes();  
  84.    String paraList = "(";  
  85.    for(int j=0; j<clzs.length; j++){  
  86.     paraList += clzs[j].getName();  
  87.     if(j != clzs.length -1 ){  
  88.      paraList += ", ";  
  89.     }  
  90.    }  
  91.    paraList += ")";  
  92.      
  93.    clzs = method.getExceptionTypes();  
  94.    String exceptions = "";  
  95.    for(int j=0; j<clzs.length; j++){  
  96.     if(j==0){  
  97.      exceptions += "throws ";  
  98.     }  
  99.   
  100.     exceptions += clzs[j].getName();  
  101.       
  102.     if(j != clzs.length -1 ){  
  103.      exceptions += ", ";  
  104.     }  
  105.    }  
  106.      
  107.    exceptions += ";";  
  108.      
  109.    String methodPrototype = modifier +retrunType+" "+methodName+paraList+exceptions;  
  110.      
  111.    System.out.println("    "+methodPrototype );  
  112.      
  113.   }  
  114.   System.out.println("}");  
  115.  }  


 

再改写main方法

 
[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public static void main(String[] args) {  
  2.   BusinessProcessorImpl bpimpl = new BusinessProcessorImpl();  
  3.   BusinessProcessorHandler handler = new BusinessProcessorHandler(bpimpl);  
  4.   BusinessProcessor bp = (BusinessProcessor)Proxy.newProxyInstance(bpimpl.getClass().getClassLoader(), bpimpl.getClass().getInterfaces(), handler);  
  5.   bp.processBusiness();  
  6.   System.out.println(bp.getClass().getName());  
  7.   Class clz = bp.getClass();  
  8.   printClassDefinition(clz);  
  9.  }  



现在我们再看看输出结果:

You can do something here before process your business
processing business.....
You can do something here after process your business
$Proxy0
$Proxy0 extends java.lang.reflect.Proxy implements com.tom.proxy.dynamic.BusinessProcessor
{
    java.lang.reflect.Method m4;
    java.lang.reflect.Method m2;
    java.lang.reflect.Method m0;
    java.lang.reflect.Method m3;
    java.lang.reflect.Method m1;

    void processBusiness();
    int hashCode();
    boolean equals(java.lang.Object);
    java.lang.String toString();
}

很明显,Proxy.newProxyInstance方法会做如下几件事:

1,根据传入的第二个参数interfaces动态生成一个类,实现interfaces中的接口,该例中即BusinessProcessor接口的processBusiness方法。并且继承了Proxy类,重写了hashcode,toString,equals等三个方法。具体实现可参看 ProxyGenerator.generateProxyClass(...); 该例中生成了$Proxy0类

2,通过传入的第一个参数classloder将刚生成的类加载到jvm中。即将$Proxy0类load

3,利用第三个参数,调用$Proxy0的$Proxy0(InvocationHandler)构造函数 创建$Proxy0的对象,并且用interfaces参数遍历其所有接口的方法,并生成Method对象初始化对象的几个Method成员变量

4,将$Proxy0的实例返回给客户端。

现在好了。我们再看客户端怎么调就清楚了。

1,客户端拿到的是$Proxy0的实例对象,由于$Proxy0实现了BusinessProcessor,因此转化为BusinessProcessor没任何问题。

BusinessProcessor bp = (BusinessProcessor)Proxy.newProxyInstance(....);

2,bp.processBusiness();

实际上调用的是$Proxy0.processBusiness();那么$Proxy0.processBusiness()的实现就是通过InvocationHandler去调用invoke方法啦!


0 0