初試 cglib
程序员文章站
2022-03-20 13:57:51
...
public class Man {
public String say() {
System.out.println("cglib hello~~~");
return "return cglib hello";
}
}
import java.lang.reflect.Method;
import net.sf.cglib.proxy.CallbackFilter;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
public class AOPInstrumenter implements MethodInterceptor,CallbackFilter {
private Enhancer enhancer = new Enhancer();
private Object sub;
public AOPInstrumenter(Object obj) {
super();
this.sub = obj;
}
public Object getInstrumentedClass(Class clz) {
enhancer.setSuperclass(clz);
//設置callback是this
enhancer.setCallback(this);
//添加 方法过滤器 返回1为不运行 0 为运行
enhancer.setCallbackFilter(this);
return enhancer.create();
}
public Object intercept(Object o, Method method, Object[] arg,
MethodProxy proxy) throws Throwable {
System.out.println("cglib 111111");
Object obj = proxy.invoke(sub, arg);
System.out.println("cglib 222222");
return obj;
}
public int accept(Method method) {
System.out.println("accept........."+method.getName());
return 0;
}
}
public class AOPTest {
public static void main(String[] args) {
Man man = new Man();
AOPInstrumenter instrumenter = new AOPInstrumenter(man);
Man man1 = (Man) instrumenter.getInstrumentedClass(Man.class);
man1.say();
}
}
運行結果:
accept.........say
accept.........hashCode
accept.........finalize
accept.........clone
accept.........equals
accept.........toString
cglib 111111
cglib hello~~~
cglib 222222
-------------------------------------------
稍作修改:
import java.lang.reflect.Method;
import net.sf.cglib.proxy.CallbackFilter;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
public class AOPInstrumenter implements CallbackFilter {
public Object getInstrumentedClass(Class clz) {
Enhancer enhancer = new Enhancer();
//设置需要代理的类
enhancer.setSuperclass(clz);
//設置callback是this
enhancer.setCallback(new ManMethodInterceptor());
//添加 方法过滤器 返回1为不运行 0 为运行
enhancer.setCallbackFilter(this);
//创建一个代理
return enhancer.create();
}
public int accept(Method method) {
System.out.println("accept........."+method.getName());
return 0;
}
}
import java.lang.reflect.Method;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
public class ManMethodInterceptor implements MethodInterceptor{
public Object intercept(Object o, Method method, Object[] arg,
MethodProxy proxy) throws Throwable {
System.out.println("cglib 111111 name: " + method);
//Object obj = proxy.invoke(o, arg);
Object obj = proxy.invokeSuper(o, arg);
System.out.println("cglib 222222");
return obj;
}
public class AOPTest {
public static void main(String[] args) {
AOPInstrumenter instrumenter = new AOPInstrumenter();
Man man1 = (Man) instrumenter.getInstrumentedClass(Man.class);
man1.say();
}
}
上一篇: 数字金额转成大写中文金额