【问题标题】:Understanding "proxy" arguments of the invoke method of java.lang.reflect.InvocationHandler了解 java.lang.reflect.InvocationHandler 的调用方法的“代理”参数
【发布时间】:2014-05-20 17:53:22
【问题描述】:

我想了解java.lang.reflect.InvocationHandler 的invoke 方法的proxy 参数的用途。

  • 应该如何以及何时使用它?
  • 它的运行时类型是什么?
  • 为什么不改用this?

【问题讨论】:

    标签: java dynamic-proxy


    【解决方案1】:

    补充彼得的回答。我添加了关于代理的 runtime-type 的以下行:

    System.out.println("accountGetClass() : " + account.getClass());
    

    哪些输出:

    accountGetClass() : class com.sun.proxy.$Proxy0
    

    【讨论】:

      【解决方案2】:

      实际上,您对实际代理几乎无能为力。尽管如此,它是调用上下文的一部分,您可以使用它通过反射获取有关代理的信息,或在后续调用中使用它(使用该代理调用另一个方法时,或作为结果。

      示例:账户类,允许存款,其deposit()方法再次返回实例以允许方法链接:

      private interface Account {
          public Account deposit (double value);
          public double getBalance ();
      }
      

      处理程序:

      private class ExampleInvocationHandler implements InvocationHandler {
      
          private double balance;
      
          @Override
          public Object invoke (Object proxy, Method method, Object[] args) throws Throwable {
      
              // simplified method checks, would need to check the parameter count and types too
              if ("deposit".equals(method.getName())) {
                  Double value = (Double) args[0];
                  System.out.println("deposit: " + value);
                  balance += value;
                  return proxy; // here we use the proxy to return 'this'
              }
              if ("getBalance".equals(method.getName())) {
                  return balance;
              }
              return null;
          }
      }
      

      及其用法示例:

      Account account = (Account) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] {Account.class, Serializable.class},
          new ExampleInvocationHandler());
      
      // method chaining for the win!
      account.deposit(5000).deposit(4000).deposit(-2500);
      System.out.println("Balance: " + account.getBalance());
      

      关于你的第二个问题:运行时类型可以使用反射来评估:

      for (Class<?> interfaceType : account.getClass().getInterfaces()) {
          System.out.println("- " + interfaceType);
      }
      

      您的第三个问题:'this' 指的是调用处理程序本身,而不是代理。

      【讨论】:

      • 非常感谢您的回答。关于我关于“this”的第三个问题:invocationHandler 实现和代理有什么区别?
      • 换句话说,为什么不返回“this”而不是“proxy”?
      • 返回这个;应该返回 InvocationHandler 实例,而不是 Account 实例。
      猜你喜欢
      • 1970-01-01
      • 2014-11-15
      • 2013-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-26
      • 2015-10-06
      • 1970-01-01
      相关资源
      最近更新 更多