CGLIB 普通用法

418 阅读1分钟
  • 定义拦截回调, 实现MethodInterceptor接口
package proxy;

import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author Mr Morning
 * @date 2019/4/30 08:54
 */
public class CglibProxy implements MethodInterceptor {

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        System.out.println("before invoke");
        methodProxy.invokeSuper(obj, args);
        System.out.println("after invoke");
        return obj;
    }
}

  • 定义被代理对象
package proxy;

/**
 * @author Mr Morning
 * @date 2019/4/30 08:56
 */
public class Run {

    public void run(){
        System.out.println("runing......");
    }
}
  • 测试
        @Test
    public void testCglib(){
        Enhancer enhancer = new Enhancer();
        // 设置被代理类
        enhancer.setSuperclass(Run.class);

        // 设置拦截回调
        enhancer.setCallback(new CglibProxy());

        // 创建代理类
        Run o = (Run) enhancer.create();

        // 判断是否为代理类
        boolean is = o.getClass().getName().contains("$$EnhancerByCGLIB?");
        System.out.println(is);
        o.run();
        System.out.println("end");
    }