程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> cglib動態代理,cglib動態

cglib動態代理,cglib動態

編輯:JAVA綜合教程

cglib動態代理,cglib動態


代理即為訪問對象添加一層控制層,使其間接化,控制層可以為對象訪問添加操作屬性。

cglib:Code Generation library,

  • 基於ASM(java字節碼操作碼)的高性能代碼生成包
  • 被許多AOP框架使用
  • 區別於JDK動態代理,cglib不需要實現接口。

實例:

 1  import java.lang.reflect.Method;  
 2    
 3  import net.sf.cglib.proxy.Enhancer;  
 4  import net.sf.cglib.proxy.MethodInterceptor;  
 5  import net.sf.cglib.proxy.MethodProxy;  
 6    
 7    
 8  public class MyMethodInterceptor implements MethodInterceptor {        
 9      
10  
11      public String myFun(String arg){  
12          return "hello," + arg ;  
13      }  
14       
15      public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {  
16          String methodName = method.getName();  
17           
18          System. out .println( "[intercept] fun invoked before" );  
19          String result = (String)args[0] + "..." ;  
20          System. out .println( result );  
21          System. out .println( "[intercept] fun invoked after" );  
22          return result;       
23      }  
24       
25      public Object createProxy(){  
26          Enhancer enhancer = new Enhancer();  
27          enhancer.setSuperclass(MyMethodInterceptor. class );  
28          enhancer.setCallback( this );  
29          return enhancer.create();  
30      }  
31       
32       
33      public static void main(String[] args) {  
34          MyMethodInterceptor ss = new MyMethodInterceptor();  
35          MyMethodInterceptor proxy = (MyMethodInterceptor)ss.createProxy();  
36 
37          c1.myFun( "cglib test" );  
38           
39      }  
40    
41  }  

 通用工具類:

 1 package org.windwant.spring.core.proxy;
 2 
 3 import org.springframework.cglib.proxy.Enhancer;
 4 import org.springframework.cglib.proxy.MethodInterceptor;
 5 import org.springframework.cglib.proxy.MethodProxy;
 6 
 7 import java.lang.reflect.Method;
 8 
 9 /**
10  * Created by windwant on 2016/6/4.
11  */
12 public class MyCGLIBProxy implements MethodInterceptor {
13     private Enhancer enhancer = new Enhancer();
14     public Object getProxy(Class clazz){
15         enhancer.setSuperclass(clazz);
16         enhancer.setCallback(this);
17         return enhancer.create();
18     }
19 
20     public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
21         System.out.println("cglib before action");
22         Object result = methodProxy.invokeSuper(o, objects);
23         System.out.println("cglib after action");
24         return result;
25     }
26 }
1 MyCGLIBProxy p = new MyCGLIBProxy();
2 Performer pp = (Performer) p.getProxy(XXXX.class);
3 pp.XXXX();

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved