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

  • 相关阅读:
    求a,b在区间上的公倍数个数
    最长非上升子序列的长度
    uva 11992 线段树
    hdu 5464 dp
    hdu 5465 树状数组
    hdu 5459 递推
    poj 2528 动态线段树
    hdu 4474 bfs
    ural 1495 bfs
    hdu 2795 线段树
  • 原文地址:https://www.cnblogs.com/mabaishui/p/5190487.html
Copyright © 2011-2022 走看看