首页 > 代码库 > 动态代理CGlib实例

动态代理CGlib实例

1.委托类;

package 动态代理2;//需要对这个类进行增强public class UserService {        public void create()    {        System.out.println("创建用户");    }    public  void update()    {        System.out.println("更新用户");            }}

2.代理类的实现

 1 package 动态代理2; 2  3 import java.lang.reflect.Method; 4  5 import net.sf.cglib.proxy.Enhancer; 6 import net.sf.cglib.proxy.MethodInterceptor; 7 import net.sf.cglib.proxy.MethodProxy; 8  9 public class ProxyCglib implements MethodInterceptor{10     //根据传入的名字来判断是否有操作权限11     private Enhancer enhancer=new Enhancer();12     13     private String name=null;14     15     public ProxyCglib(String name)16     {17         this.name=name;18         19     }20     //获得代理类的对象,传入参数为委托类21     public Object getProxy(Class clazz){22           //设置需要创建子类的类23           enhancer.setSuperclass(clazz);24           enhancer.setCallback(this);25           //通过字节码技术动态创建子类实例26           return enhancer.create();27          }28 29 30     31     public Object intercept(Object arg0, Method arg1, Object[] arg2,32             MethodProxy arg3) throws Throwable {33         // TODO Auto-generated method stub34         35         if(!name.equals("han"))36         {37          System.out.println("权限不足");38         }39         else40         {41             arg3.invokeSuper(arg0, arg2);42             43         }44         45         return null;46     }47     48 49 }

3.客户端:测试

package 动态代理2;//ref: http://songbo-mail-126-com.iteye.com/blog/968792public class Test {    public static void main(String[] args) {        // TODO Auto-generated method stub        //为用户张三创建一个代理对象    /*            ProxyCglib proxy=new ProxyCglib("张三");        UserService user=(UserService) proxy.getProxy(UserService.class);        user.create(); */                ProxyCglib proxy2=new ProxyCglib("han");        UserService user2 =(UserService) proxy2.getProxy(UserService.class);        user2.create();                }}

 

动态代理CGlib实例