CglibProxy

package com.yusb.proxy.cglib;

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

import java.lang.reflect.Method;

/**
 * @author : yushibin
 * @version : 1.0
 * @date : 2021-03-17 21:39
 * @description :
 */
public class TargetCglibProxy implements MethodInterceptor {

    private Object target;

    public TargetCglibProxy(Object target) {
        this.target = target;
    }

    public Object getTargetProxy(){
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(this);
        Object proxy = enhancer.create();
        return proxy;
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

        System.out.println("target method execute before......");

        Object obj = methodProxy.invoke(target, objects);

        System.out.println("target method execute after......");

        return obj;
    }
}

 

posted @ 2021-03-17 22:09  发丝有些凌乱丶  阅读(55)  评论(0编辑  收藏  举报