zoukankan      html  css  js  c++  java
  • 动态代理案例2://需求:控制参数*2,返回值*2

    动态代理案例2://需求:控制参数*2,返回值*2

      1 import java.lang.reflect.InvocationHandler;
      2  import java.lang.reflect.InvocationTargetException;
      3  import java.lang.reflect.Method;
      4  import java.lang.reflect.Proxy;
      5 
      6 //接口
      7 interface A {
      8      public void show1(int a);
      9 
     10     public int show2(int a);
     11  }
     12 
     13 // 实现类
     14 class B implements A {
     15      @Override
     16      public void show1(int a) {
     17          System.out.println("show1方法的参数值为:" + a);
     18      }
     19 
     20     @Override
     21      public int show2(int a) {
     22         return a;
     23      }
     24  }
     25 
     26 // 访问者
     27 public class Demo {
     28      public static void main(String[] args) {
     29          // 创建代理对象
     30         A obj = (A) Proxy.newProxyInstance(B.class.getClassLoader(),B.class.getInterfaces(), new InvocationHandler() {
     31                      @Override
     32                      public Object invoke(Object proxy, Method method,Object[] args) {
     33                          // 参数扩大两倍
     34                         for (int i = 0; i < args.length; i++) {
     35                              if (args[i] instanceof Integer) {
     36                                  Integer a = (Integer) args[i];
     37                                  a *= 2;// 扩大两倍
     38                                 args[i] = a;
     39                              }
     40                          }// for(i)
     41 
     42                         Object obj = null;
     43                          try {
     44                              obj = method.invoke(new B(), args);
     45                          } catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException e) {
     46                              e.printStackTrace();
     47                          }
     48 
     49                         // 返回值扩大两倍
     50                         if (obj instanceof Integer) {
     51                              Integer a = (Integer) obj;
     52                              a *= 2;
     53                              return a;
     54                          }
     55                          return obj;
     56                      }
     57                  }// new InvocationHandler
     58                  );
     59          // 由代理对象调用方法(已加强)
     60          obj.show1(10);// show1方法的参数值为:20
     61          System.out.println("show2方法的返回值为:" + obj.show2(10));// show2方法的返回值为:40
     62      }
     63  }
     64 
  • 相关阅读:
    html 中 url、scr、href、rel、rev
    MIME 和文件扩展名
    视频文件的容器格式和编码格式
    原型与原型链
    属性特征
    可选参数
    函数的定义(函数是值)
    闭包
    实现异步加载js文件及加载完成后回调
    前端工程打开速度优化的循序渐进总结
  • 原文地址:https://www.cnblogs.com/huguangqin/p/7137552.html
Copyright © 2011-2022 走看看