package com.jy.util; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; import org.apache.poi.ss.formula.functions.T; import java.lang.reflect.Method; public class MyCglibProxyDemo implements MethodInterceptor{ /* <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>3.2.5</version> </dependency> */ private T target; public T getInstance(T target){ this.target = target; Enhancer enhancer = new Enhancer();
//指定被代理的作为父类 enhancer.setSuperclass(target.getClass()); enhancer.setCallback(this); return (T)enhancer.create(); } @Override public Object intercept(Object obj, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { //前置处理 Object invoke = methodProxy.invoke(obj, objects); //后置处理 return invoke; } }