Understanding the "proxy" arguments of the invoke method for java.lang.reflect.InvocationHandler

I would like to understand the purpose of the proxymethod argument .invoke java.lang.reflect.InvocationHandler

  • How and when should it be used?
  • What is its runtime type?
  • Why not use it thisinstead?
+4
source share
2 answers

In fact, little can be done with the actual proxy. Nevertheless, this is part of the call context, and you can use it to obtain information about the proxy server using reflection or use it in subsequent calls (when calling another method with this proxy server or as a result.

: acccount, , deposit() , :

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

Handler:

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" , .

+3

. :

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

:

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

Source: https://habr.com/ru/post/1535497/


All Articles