cglib
1、概述
1.1、CGLIB(Code Generation Library)是一个开源项目;
1.2、是一个强大的,高性能,高质量的Code生成类库,它可以在运行期扩展Java类与实现Java接口;
1.3、CGLIB包的底层 是 通过使用一个小而快的字节码处理框架ASM,来转换字节码并生成新的类;
2、案例
package com.an.bytecode.cglib; /** * @description: * @author: anpeiyong * @date: Created in 2020/4/7 15:25 * @since: */ public class Dao { public void update() { System.out.println("update..."); } } package com.an.bytecode.cglib; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; import java.lang.reflect.Method; /** * @description: * @author: anpeiyong * @date: Created in 2020/4/7 15:26 * @since: */ public class MyProxy implements MethodInterceptor { /** * * @param object 要增强的对象 * @param method 拦截的方法 * @param params * @param methodProxy 对方法的代理 * @return * @throws Throwable */ @Override public Object intercept(Object object, Method method, Object[] params, MethodProxy methodProxy)throws Throwable{ System.out.println("before..."); methodProxy.invokeSuper(object,params); System.out.println("after..."); return null; } } package com.an.bytecode.cglib; import net.sf.cglib.proxy.Enhancer; /** * @description: * @author: anpeiyong * @date: Created in 2020/4/7 14:56 * @since: */ public class Test { public static void main(String[] args) { MyProxy proxy=new MyProxy(); Enhancer enhancer=new Enhancer(); enhancer.setSuperclass(Dao.class); enhancer.setCallback(proxy); Dao dao=(Dao) enhancer.create(); dao.update(); } } 结果: before... update... after...