java Cglib的应用

阅读更多
  java中简单使用CGLIB实现AOP的切面编程
package ppfuns.cglib;

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

import java.lang.reflect.Method;

/**
 * Created with IntelliJ IDEA.
 * Date: 2018/1/12
 * Time: 11:11
 * To change this template use File | Settings | File Templates.
 */
public class EnhancerDemo {

    public static void main(String[] args) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(EnhancerDemo.class);
        enhancer.setCallback(new MethodInterceptorImpl());
        EnhancerDemo demo = (EnhancerDemo) enhancer.create();
        demo.test();
        System.out.println(demo);
    }
    public void test(){
        System.out.println("正在测试:"+EnhancerDemo.class.getName());
    }
}
class MethodInterceptorImpl implements MethodInterceptor{
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("before test....."+method.getName());
        Object t =  methodProxy.invokeSuper(o,objects);
        System.out.println("after test ...."+method.getName());
        return t;
    }
}


结果:
before test.....test
正在测试:ppfuns.cglib.EnhancerDemo
after test ....test
before test.....toString
before test.....hashCode
after test ....hashCode
after test ....toString
ppfuns.cglib.EnhancerDemo$$EnhancerByCGLIB$$fdf1bbc4@6ae40994

Process finished with exit code 0

你可能感兴趣的:(java,aop)