當前位置:編程學習大全網 - 源碼下載 - java InvocationHandler invoke方法的第壹個參數有什麽用

java InvocationHandler invoke方法的第壹個參數有什麽用

1. 可以使用反射獲取代理對象的信息(也就是proxy.getClass().getName())。

2. 可以將代理對象返回以進行連續調用,這就是proxy存在的目的。因為this並不是代理對象,

下面看源代碼

接口:

[java]?view plain?copy

private?interface?Account?{?

public?Account?deposit?(double?value);?

public?double?getBalance?();?

}?

Handler:

[java]?view plain?copy

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;?

}?

}?

使用:

[java]?view plain?copy

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());?

我們看到如果返回proxy的話可以對該代理對象進行連續調用

那為什麽不返回this,而是返回proxy對象呢?

因為this對象的類型是ExampleInvocationHandler,而不是代理類$Proxy0

除此之外,不返回代理對象的話,還能返回其他信息,如balance。

  • 上一篇:求災難片,恐怖,科幻電影
  • 下一篇:學會賣生活方式,拯救朋友圈不賺
  • copyright 2024編程學習大全網