zoukankan      html  css  js  c++  java
  • 动态代理的几种方式

    动态代理有Java Proxy,CGLib,JAVAssist等几种实现方式。

    1、初探java的Proxy+InvocationHandler

    reference:http://m.oschina.net/blog/224931

    English page:https://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Proxy.html

     1 public interface Colorable {
     2 
     3     public void value();
     4     
     5 }
     6 
     7 public class RedColor implements Colorable {
     8 
     9     @Override
    10     public void value() {
    11         System.out.println("--------------red-------------");
    12     }
    13 
    14 }
    15 
    16 public class ColorableProxy implements InvocationHandler {
    17 
    18     private Colorable colorable;
    19     private Colorable proxy;
    20     
    21     public ColorableProxy(Colorable colorable) {
    22         this.colorable = colorable;
    23         this.proxy = (Colorable)Proxy.newProxyInstance(Colorable.class.getClassLoader(), new Class<?>[] { Colorable.class }, this);
    24     }
    25     
    26     public Colorable getProxy() {
    27         return proxy;
    28     }
    29     
    30     @Override
    31     public Object invoke(Object proxy, Method method, Object[] args)
    32             throws Throwable {
    33         String methodName = method.getName();
    34 
    35         System.out.println("===========starting invoke function:" + methodName + "==========");
    36         
    37         Object result = method.invoke(colorable, args);
    38         
    39         System.out.println("=========== invoke function:" + methodName + " success==========");
    40         return result;
    41     }
    42 
    43 }
    44 
    45 public class Main {
    46 
    47     public static void main(String[] args) {
    48         
    49         Colorable proxy = new ColorableProxy(new RedColor()).getProxy();
    50         proxy.value();
    51     }
    52 
    53 }

     2、几种动态代理的比较:http://it.deepinmind.com/java/2014/02/24/%E5%8A%A8%E6%80%81%E4%BB%A3%E7%90%86%E5%AE%9E%E7%8E%B0%E7%9A%84%E6%AF%94%E8%BE%83.html

  • 相关阅读:
    使用redis配置分布式session
    邮件发送整合
    Spark基础-scala学习(八、隐式转换与隐式参数)
    QMQ去哪儿网-mq中间件(启动失败)
    Spark基础-scala学习(七、类型参数)
    JMH实践-代码性能测试工具
    Spark基础-scala学习(五、集合)
    [JavaWeb基础] 012.Struts2 自定义标签使用
    html5学习之路_003
    [Objective-C] 017_UI篇_UIView(中)
  • 原文地址:https://www.cnblogs.com/mabaishui/p/5190487.html
Copyright © 2011-2022 走看看