InvocationHandler中invoke方法中的第一个参数proxy的用途

https://stackoverflow.com/questions/22930195/understanding-proxy-arguments-of-the-invoke-method-of-java-lang-reflect-invoca

 

There's in fact little you can do with the actual proxy. Nevertheless it's part of the invocation context, and you can use it to gain information on the proxy using reflection, or use it in subsequent calls (when calling another method with that proxy, or as a result.

Example: an acccount class, which allows to deposit money, whose deposit() method returns the instance again to allow method chaining:

privateinterface Account
   {
   publicAccount deposit (double value)
   publicdouble getBalance ();

   }

Handler:

private class ExampleInvocationHandler implements InvocationHandler{

privatedouble 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;
}

}

And an example of its usage:

Account account =(Account)Proxy.newProxyInstance

(getClass().getClassLoader(),

newClass[]{Account.class,Serializable.class},

newExampleInvocationHandler());// method chaining for the win!
account.deposit(5000).deposit(4000).deposit(-2500);

System.out.println("Balance: "+ account.getBalance());

As for your second question: the runtime type can be evaluated using reflection:

for(Class<?> interfaceType : account.getClass().getInterfaces()){

System.out.println("- "+ interfaceType);

}

And your third question: 'this' would refer to the invocation handler itself, not the proxy.

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值