cglib动态代理举例

jdk的动态代理是基于接口的代理,而cglib不要求实现接口,是一种基于继承的代理,使用字节码生成被代理类的子类

 

public class TestMethodInterceptor implements MethodInterceptor {

    private Object targetObject;

    public TestMethodInterceptor(Object target){
        this.targetObject = target;
    }

    public Object getProxyInstance() {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(targetObject.getClass());
        enhancer.setCallback(this);
        Object proxy = enhancer.create();
        return proxy;
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("intercept begin");
        System.out.println("class:" + o.getClass().getName() + ", method:"+ method.getName());
        System.out.println("class:" + methodProxy.getClass().getName() + ", method:"+ method.getName());
        methodProxy.invokeSuper(o,objects);
        method.invoke(targetObject,objects);
        System.out.println("intercept end");
        return null;
    }

}
    public static void main(String[] args) {
        SayImpl sayProxy = (SayImpl)new TestMethodInterceptor(new SayImpl()).getProxyInstance();
        sayProxy.sayHello("my dear");
    }

 

执行结果:

intercept begin
class:com.cainiao.wmpinbound.refund.job.register.node.SayImpl$$EnhancerByCGLIB$$1e0a054, method:sayHello
class:org.springframework.cglib.proxy.MethodProxy, method:sayHello
hello:my dear
hello:my dear
intercept end

 

posted @ 2017-12-25 13:53  此生重演  阅读(327)  评论(0编辑  收藏  举报