java代理

jdk动态代理

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

/**

  • @author

  • @date 2022/5/23

  • @Description
    */
    public class JDKInvocationTest {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {

     //cglib代理
    

// MaoTaiSellImpl target = new MaoTaiSellImpl();
// MaoTaiSellImpl proxyFactory = (MaoTaiSellImpl)new ProxyFactory(target).getProxyInstance();
// int sell = proxyFactory.sell(10);
// System.out.println(“原价-”+10000+" 现价-"+sell);

    //jdk代理
    MaoTaiSellImpl target = new MaoTaiSellImpl();
    InvocationHandler handler = new MySellWineInvocationHandler(target);
    SellWine wo = (SellWine)Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), handler);
    int price = wo.sell(10);
    System.out.println("原价-"+10000+" 现价-"+price);
}

}``
//接口
public interface SellWine {
int sell(int amount);
}
//实现类
public class MaoTaiSellImpl implements SellWine {
@Override
public int sell(int amount) {
int a = amount*1000;
return a;
}
}

//jdk代理实现
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**

  • @author

  • @date 2022/5/23

  • @Description
    */
    public class MySellWineInvocationHandler implements InvocationHandler {

    private Object target;

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

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    Object feeObj = method.invoke(target, args);
    int feeAmount = (int)feeObj;
    int totalFee = feeAmount + (feeAmount/10);
    return totalFee;
    }
    }

//cglib代理
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**

  • @author zhoujunfan

  • @date 2022/5/23

  • @Description
    */
    public class ProxyFactory implements MethodInterceptor {

    //目标对象
    private Object target;

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

    public Object getProxyInstance(){
    Enhancer en = new Enhancer();
    en.setSuperclass(target.getClass());
    en.setCallback(this);
    return en.create();
    }


CGLib创建的动态代理对象性能比JDK创建的动态代理对象的性能高不少,但CGLib在创建代理对象时所花费的时间却比JDK多得多,所以对于单例对象,因无需频繁创建对象,用CGLib合适,反之,使用JDK方式要更为合适一些。同时,由于CGLib由于是采用动态创建子类的方法,对于final方法,无法进行代理。

静态代理  参考  实现runable接口开启线程
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值