java - 理解 java.lang.reflect.InvocationHandler 的 invoke 方法的 "proxy"参数

标签 java dynamic-proxy

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

  • 应该如何以及何时使用它?
  • 它的运行时类型是什么?
  • 为什么不用 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”指的是调用处理程序本身,而不是代理。

关于java - 理解 java.lang.reflect.InvocationHandler 的 invoke 方法的 "proxy"参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22930195/

相关文章:

java - 为什么AIDL接口(interface)不能使用代理?

java - 在 GUI 中显示 Java 控制台

java - 无法对非静态方法进行静态引用 (Java)

java - 使用layout.swipe从页面适配器中删除特定位置页面

java - 在运行时增强 java 对象

language-agnostic - C# 委托(delegate)、动态代理、闭包和函数指针之间有什么区别?

c# - 如何在没有类实例的情况下获取EF动态代理类的类型

java - dicom 小程序查看器

用于创建 Ajax 网站的 Java 框架(相对于 Web 应用程序)