cglib动态代理和jdk代理不一样,它不需要代理类实现接口,所有的非final方法都可以被代理,它有一个方法拦截器MethodInterceptor,就是对方法进行增强的,下面来看看
//需要被代理的类
public class Customer {
public void buy(int x){
System.out.println("买了一本书,"+x+"元");
}
}
//代理类
public class Proxy {
private Customer target;
public void setTarget(Customer target){
this.target=target;
}
public Customer getProxy(){
Enhancer enhancer=new Enhancer();
enhancer.setSuperclass(target.getClass());
enhancer.setCallback(new MethodInterceptor() {
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("代理开始");
Object obj=methodProxy.invokeSuper(o,objects);
System.out.println("代理结束");
return obj;
}
});
Customer o=(Customer)enhancer.create();
return o;
}
}
//测试类
public class Test {
public static void main(String[]args){
Proxy p=new Proxy();
p.setTarget(new Customer());
p.getProxy().buy(12);
}
}
//代理开始
//买了一本书,12元
//代理结束