JAVA 两种代理实现

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

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

class JDKProxy implements InvocationHandler{

    private Object targetObject;

    public Object newProxy(Object targetObject){
        this.targetObject = targetObject;
        return Proxy.newProxyInstance(targetObject.getClass().getClassLoader(),targetObject.getClass().getInterfaces(),this);
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object ret = null;;
        ret = method.invoke(targetObject,args);
        return null;
    }
}

class CGLibProxy implements MethodInterceptor {

    private Object targetObject;
    public Object newProxy(Object object){
        this.targetObject = object;
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(object.getClass());
        enhancer.setCallback(this);
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        Object ret = null;
        ret = method.invoke(targetObject,objects);
        return ret;
    }
}

 

posted @ 2020-06-08 14:52  fireflyover  阅读(241)  评论(0编辑  收藏  举报