Java:CGLib动态代理实现原始类的扩展

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

参考
CGLib动态代理

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页