cglib 子类代理

public class MyCiglibProxy implements MethodInterceptor {
 
 private Object obj;//目标对象
 
 public Object getCiglibProxy(Object obj){
  this.obj = obj;//初始化目标对象
  Enhancer enhancer = new Enhancer();
  enhancer.setSuperclass(obj.getClass());//为代理类指定父类
  enhancer.setCallback(this);//代理类方法  都会调用intercept
  //创建动态代理类
  return enhancer.create();
 }
 
 
 
 @Override
 public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
  
  System.out.println("before.....");
  proxy.invokeSuper(obj, args);//调用业务类 的父类方法
  System.out.println("after.....");
  return null;
 }
 
 public static void main(String[] args) {
  MyCiglibProxy p = new MyCiglibProxy();
  Studentq s = (Studentq) p.getCiglibProxy(new Studentq());
  s.say();
  
 }
}
class Studentq{
 public void say(){
  System.out.println("aaa");
 }
}
 

猜你喜欢

转载自www.cnblogs.com/PG-five/p/9318080.html