簡體   English   中英

了解java.lang.reflect.InvocationHandler的invoke方法的“代理”參數

[英]Understanding “proxy” arguments of the invoke method of java.lang.reflect.InvocationHandler

我想了解java.lang.reflect.InvocationHandlerinvoke方法的proxy參數的用途。

  • 應如何以及何時使用?
  • 它的運行時類型是什么?
  • 為什么不使用this呢?

實際上,使用實際代理幾乎無濟於事。 盡管如此,它還是調用上下文的一部分,您可以使用它通過反射來獲取有關代理的信息,或者在后續調用中使用該代理(當使用該代理調用另一個方法時,或者作為結果)。

示例:一個允許存款的帳戶類,其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 ”是指調用處理程序本身,而不是代理。

補充彼得的回答。 我添加了以下有關代理的運行時類型的行:

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

哪個輸出:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM