简单的代理-cglib代理
1 一个简单的类
public class Dog {
public void sayHi(String name) {
System.out.println("汪汪------"+name);
}
}
2 实现MethodInterceptor接口完成代理
public class CglibDemo implements MethodInterceptor {
private Object target;
public Object getTarget(Object target){
this.target =target;
Enhancer enhancer =new Enhancer();
enhancer.setSuperclass(target.getClass());
enhancer.setCallback(this);
return enhancer.create();
}
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("start---");
Object returnObj = methodProxy.invokeSuper(o, objects);
System.out.println("end---");
return returnObj;
}
public static void main(String[] args) {
CglibDemo cglibDemo =new CglibDemo();
Dog target = (Dog)cglibDemo.getTarget(new Dog());
target.sayHi("pp");
}
}