Github: https://github.com/cglib/cglib
依赖
<dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>3.3.0</version> </dependency>
目标类
package com.demo.cgbib; public class Dog { public void sayHello(String name){ System.out.println("Hello " + name); } }
方法拦截器
package com.demo.cgbib; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; import java.lang.reflect.Method; public class LogInterceptor implements MethodInterceptor { @Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { System.out.println("before"); // 调用父类方法,不是反射 Object result = proxy.invokeSuper(obj, args); System.out.println("after"); return result; } }
测试类
package com.demo.cgbib; import net.sf.cglib.proxy.Enhancer; public class Demo { public static void main(String[] args) { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(Dog.class); enhancer.setCallback(new LogInterceptor()); Dog dog = (Dog) enhancer.create(); dog.sayHello("Tom"); } }
输出结果
before Hello Tom after