有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (2) 个答案

  1. # 1 楼答案

    补充彼得的回答。我添加了以下关于代理的运行时类型的行:

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

    哪些产出:

    accountGetClass() : class com.sun.proxy.$Proxy0
    
  2. # 2 楼答案

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

    示例:允许存款的acccount类,其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”指的是调用处理程序本身,而不是代理