动态代理CGlib实例

1.委托类;

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

2.代理类的实现

 package 动态代理2;

 import java.lang.reflect.Method;

 import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy; public class ProxyCglib implements MethodInterceptor{
//根据传入的名字来判断是否有操作权限
private Enhancer enhancer=new Enhancer(); private String name=null; public ProxyCglib(String name)
{
this.name=name; }
//获得代理类的对象,传入参数为委托类
public Object getProxy(Class clazz){
//设置需要创建子类的类
enhancer.setSuperclass(clazz);
enhancer.setCallback(this);
//通过字节码技术动态创建子类实例
return enhancer.create();
} public Object intercept(Object arg0, Method arg1, Object[] arg2,
MethodProxy arg3) throws Throwable {
// TODO Auto-generated method stub if(!name.equals("han"))
{
System.out.println("权限不足");
}
else
{
arg3.invokeSuper(arg0, arg2); } return null;
} }

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(); } }
上一篇:Hadoop学习(3)-- 安装1.x版本


下一篇:神经网络、logistic回归等分类算法简单实现