动态代理案例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