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 stub 34 35 if(!name.equals("han")) 36 { 37 System.out.println("权限不足"); 38 } 39 else 40 { 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/968792 public 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(); } }
时间: 2024-10-06 10:11:14