java中的代理

代理可以理解为中间销售,存在于用户和生产厂家中间,负责两边的联系,厂家的产品通过销售卖给用户,用户所购买的产品出现损坏通过销售来进行售后,用户和厂家不进行直接沟通,降低了方法中的耦合问题

基于借口的代理

Proxy!!!

Proxy所代理的类必须要有一个接口实现

 public static void main(String[] args) {
        final Producer producer=new Producer();
        IProducer iProducer= (IProducer) Proxy.newProxyInstance(producer.getClass().getClassLoader(), producer.getClass().getInterfaces(), new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object returnValue=null;
                Float money= (Float) args[0];
                if("saleProduct".equals(method.getName())){
                    returnValue=method.invoke(producer,money*0.8f);
                }
                return returnValue;
            }
        });
        iProducer.saleProduct(100000f);

    }
newProxyInstance有三个参数
  1. ClassLoader:类加载器,通过类方法.getClass().getClassLoader()获得
  2. class[]:类中的方法列表,通过.getClass().getInterfaces()获得
  3. InvocationHandler:提供增强代码,一般放入内部内,实现new InvocationHandler(),method为执行的方法,args是方法中所需要的参数

基于子类的代理

cglib

需要引入cglib包来使用

 <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.1_3</version>
        </dependency>
  public static void main(final String[] args) {
      final Producer producer=new Producer();

      Producer cglibproducer= (Producer) Enhancer.create(producer.getClass(), new MethodInterceptor() {
          public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
              Object returnValue=null;
              Float money= (Float) args[0];
              if("saleProduct".equals(method.getName())){
                  returnValue=method.invoke(producer,money*0.8f);
              }
              return returnValue;
          }
      });
      cglibproducer.saleProduct(100000);

    }

Enhancer.create被代理类不能是最终类(最终类是指不能被继承的类,即不能再用最终类派生子类。在Java语言中,如果不希望某类被继承,可以声明这个类为最终类。最终类用关键字final来说明)public final class FinalClass{}

Enhancer.create有两个参数
  1. class:被代理对象的字节码,通过.getClass()获得
  2. Callback:用于提供增强代码,一般实现new MethodInterceptor()基本参数与借口代理类似
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小学弟QAQ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值