java動態(tài)代理與CGLib代理示例代碼

被代理服務(wù)接口定義與實現(xiàn)

接口定義


public interface Hello {
   void sayHello();
}

服務(wù)實現(xiàn)


public class HelloImpl implements Hello {

   @Override
   public void sayHello() {
       System.out.println("hello world");
   }
}

動態(tài)代理類


public class DynamicProxy implements InvocationHandler {

   private Object target;

   public DynamicProxy(Object target) {
       this.target = target;
   }

   @Override
   public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
       before();
       Object result = method.invoke(target, args);
       after();
       return result;
   }

   private void before() {
       System.out.println("before");
   }

   private void after() {
       System.out.println("result");
   }
}

使用


public static void main(String[] args) {
   Hello hello1 = new HelloImpl();
   Hello hello2 = new HelloImpl2();
   List<Hello> helloList = new ArrayList<Hello>();
   helloList.add(hello1);
   helloList.add(hello2);
   for (Hello hello : helloList) {
       Hello helloProxy = getHelloService(hello);
       helloProxy.sayHello();
   }
}

public static Hello getHelloService(Hello hello) {
   DynamicProxy dynamicProxy = new DynamicProxy(hello);
   return (Hello)Proxy.newProxyInstance(
           hello.getClass().getClassLoader(),
           hello.getClass().getInterfaces(),
           dynamicProxy);
}

CGLib代理


public class CGLibProxy implements MethodInterceptor {

   private static CGLibProxy instance = new CGLibProxy();

   public static CGLibProxy getInstance() {
       return instance;
   }

   public <T> T getProxy(Class<T> cls) {
       return (T) Enhancer.create(cls, this);
   }

   public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
       before();
       Object result = proxy.invokeSuper(obj, args);
       after();
       return result;
   }

   private void before() {
       System.out.println("before");
   }

   private void after() {
       System.out.println("result");
   }
}

使用


public class App {
   public static void main(String[] args) {
       Hello helloProxy = CGLibProxy.getInstance().getProxy(HelloImpl.class);
       helloProxy.sayHello();
   }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,914評論 18 139
  • 從三月份找實習(xí)到現(xiàn)在,面了一些公司,掛了不少,但最終還是拿到小米、百度、阿里、京東、新浪、CVTE、樂視家的研發(fā)崗...
    時芥藍(lán)閱讀 42,366評論 11 349
  • 國家電網(wǎng)公司企業(yè)標(biāo)準(zhǔn)(Q/GDW)- 面向?qū)ο蟮挠秒娦畔?shù)據(jù)交換協(xié)議 - 報批稿:20170802 前言: 排版 ...
    庭說閱讀 11,141評論 6 13
  • Sierra無法安裝互聯(lián)網(wǎng)上下載的應(yīng)用? 在安全與隱私里面也沒了“任何來源”的選項 那我們怎么安裝在網(wǎng)上下載的應(yīng)用...
    阿修哥閱讀 253評論 0 5
  • C讀經(jīng): - 詩篇7:10 神是我的盾牌.他拯救心正直的人。 神看重的是心的正直。如果我們做好自己的本份,做個正直...
    NCNeverland閱讀 130評論 0 0