利用cglib与asm包的method拦截(动态代理)

  1. package graph;   
  2.   
  3. import java.lang.reflect.Method;   
  4. import java.util.HashMap;   
  5. import java.util.Map;   
  6.   
  7. import org.apache.log4j.Logger;   
  8.   
  9. import net.sf.cglib.proxy.Enhancer;   
  10. import net.sf.cglib.proxy.MethodInterceptor;   
  11. import net.sf.cglib.proxy.MethodProxy;   
  12.   
  13. public class MehtodProcessingTimesProxy implements MethodInterceptor {   
  14.   
  15.     private Enhancer enhancer = new Enhancer();   
  16.   
  17.     private Map<String, Long> map = new HashMap<String, Long>();   
  18.   
  19.      Logger log = Logger.getLogger(MehtodProcessingTimesProxy.class);   
  20.   
  21.     public Object intercept(Object o, Method method, Object[] args, MethodProxy proxy) throws Throwable {   
  22.          Long start = System.currentTimeMillis();   
  23.          Object result = proxy.invokeSuper(o, args);   
  24.          Long end = System.currentTimeMillis();   
  25.         if (!map.containsKey(method.toGenericString())) {   
  26.              map.put(method.toGenericString(), Long.valueOf(end - start));   
  27.              log.debug(method.toGenericString() + " " + (end - start) + "ms");   
  28.          }   
  29.   
  30.         return result;   
  31.      }   
  32.   
  33.     public Object ProxyFactory(Class clazz) {   
  34.          enhancer.setSuperclass(clazz);   
  35.          enhancer.setCallback(this);   
  36.         return enhancer.create();   
  37.      }   
  38.   
  39. }  
  40. 下面是实例:
  41. package graph;   
  42.   
  43. public class ATest {   
  44.   
  45.     public void method() {   
  46.         long j = 0;   
  47.         for (long i = 0; i < 1000000000; i++) {   
  48.              j += i;   
  49.          }   
  50.      }   
  51.   
  52.     public void method1() {   
  53.         long j = 0;   
  54.         for (long i = 0; i < 1000000000; i++) {   
  55.              j += i;   
  56.          }   
  57.      }   
  58.   
  59.     public void method2() {   
  60.         long j = 0;   
  61.         for (long i = 0; i < 1000000000; i++) {   
  62.              j += i;   
  63.          }   
  64.      }   
  65.   
  66.     public void method3() {   
  67.          method();   
  68.          method1();   
  69.          method2();   
  70.          method();   
  71.      }   
  72.   
  73.     public static void main(String[] args) {   
  74.          MehtodProcessingTimesProxy proxy = new MehtodProcessingTimesProxy();   
  75.          ATest t = (ATest) proxy.ProxyFactory(ATest.class);   
  76.          t.method();   
  77.          t.method1();   
  78.          t.method2();   
  79.          t.method();   
  80.          t.method3();   
  81.      }   
  82.   
  83. }  
原文地址:https://www.cnblogs.com/xinzhuangzi/p/4100617.html