静态代理&动态代理&CGlib代理

静态代理

public interface Hello{
    void say(String name);
}

public class HelloImpl implements Hello{
    @Override
    public void say(String name){
        System.out.println("Hello! "+name);
    }    
}

public class HelloProxy implements Hello{
    private Hello hello;
    
    public HelloProxy(){
        hello = new HelloImpl()
    }

    @Override
    public void say(String name){
        before();
        hello.say(name);
        after();
    }

    private void before(){
        System.out.println("Before");
    }

    private void after(){
        System.out.println("after");
    }

}

动态代理

public class DynamicProxy implements InvocationHandler{
    private Object target;

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

    @Override
    public Object invoke(Object proxy,Method method,Object[] args)throws Throwable{
        before();
        Object result = method.invoke(target,args);
        after();
        return result;
    }

    @SuppressWarnings("unchecked")
    public <T> T getProxy(){
        return (T) Proxy.newProxyInstance(
            target.getClass().getClassLoader(),
            target.getClass().getInterfaces(),
            this
        );
    }

    private void before(){
        System.out.println("Before");
    }

    private void after(){
        System.out.println("after");
    }

}

CGLib代理

public class CGLibProxy implements MethodInterceptor{

    private static CGLibProxy instance = new CGLibProxy();

    private CGLibProxy(){
        
    }

    public static CGLibProxy getInstance(){
        return instance;
    }

    public <T> T getProxy(Class<T> cls){
        return (T) Enhancer.create(cls,this);
    }

    public Object intercept(Object obj,Method method,Object[] args,MethodProxy proxy)throws Throwable{
        before();
        Object result = proxy.invokeSuper(obj,args);
        after();
        return result;
    }

    private void before(){
        System.out.println("Before");
    }

    private void after(){
        System.out.printin("after");
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值