首页 > 代码库 > 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  }  

 

cglib动态代理