白季飞龙的个人主页

CGLib大杂烩

示例代码

Foo.java

package bj.demo;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;

/**
 * Created by baijifeilong@gmail.com at 2018/6/1 上午9:58
 */
public class Foo {

    // Must not be private
    void alpha() {
        System.out.println("alpha");
    }

    public static void main(String[] args) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(Foo.class);
        enhancer.setCallback((MethodInterceptor) (o, method, objects, methodProxy) -> {
            System.out.println("Before " + methodProxy.getSuperName());
            Object result = methodProxy.invokeSuper(o, objects);
            System.out.println("After " + methodProxy.getSuperName());
            return result;
        });
        Foo foo = (Foo) enhancer.create();
        foo.alpha();
    }
}

文章首发: https://baijifeilong.github.io


漫漫路,莫论逍遥;潜心修,只为悟道