基于子类的动态代理:
生活随笔
收集整理的這篇文章主要介紹了
基于子类的动态代理:
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
基于子類的動態代理:
提供者:第三方的CGLib,如果報asmxxxx異常,需要導入asm.jar。
<dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.1_3</version> </dependency>要求:
被代理類不能用final修飾的類(最終類)。
涉及的類:
Enhancer
如何創建代理對象:
使用Enhancer類中的create方法
create方法的參數:
Class:字節碼
它是用于指定被代理對象的字節碼。
Callback:用于提供增強的代碼
它是讓我們寫如何代理。我們一般都是些一個該接口的實現類,通常情況下都是匿名內部類,但不是必須的。
此接口的實現類都是誰用誰寫。
我們一般寫的都是該接口的子接口實現類:MethodInterceptor
1 Producer cglibProducer = (Producer)Enhancer.create(producer.getClass(), new MethodInterceptor() { 2 /** 3 * 執行被代理對象的任何方法都會經過該方法 4 * @param proxy 5 * @param method 6 * @param args 7 * 以上三個參數和基于接口的動態代理中invoke方法的參數是一樣的 8 * @param methodProxy :當前執行方法的代理對象 9 * @return 10 * @throws Throwable 11 */ 12 public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { 13 //提供增強的代碼 14 15 //獲取方法執行的參數 16 Object returnValue = method.invoke(producer, args[0]); 17 } 18 return returnValue; 19 } 20 }); 21 cglibProducer.saleProduct(12000f);?
轉載于:https://www.cnblogs.com/mkl7/p/10691939.html
總結
以上是生活随笔為你收集整理的基于子类的动态代理:的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 阿里云服务器ubuntu14.04安装R
- 下一篇: 用户管理和su,id 命令