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.
本文介绍了一个使用Java反射API实现的代理模式案例。通过定义接口和InvocationHandler,文章展示了如何利用代理对象进行方法调用,实现存款操作的方法链接,并通过反射获取运行时类型。
453

被折叠的 条评论
为什么被折叠?



