InvocationHandler中invoke方法中的第一個參數proxy的用途

來自:http://blog.csdn.net/bu2_int/article/details/60150319

最近在研究Java的動態代理時對InvocationHandler中invoke方法中的第一個參數一直不理解它的用處,某度搜索也搜不出結果,最後終於在stackoverflow上找到了答案。

這是原文的鏈接:http://stackoverflow.com/questions/22930195/understanding-proxy-arguments-of-the-invoke-method-of-java-lang-reflect-invoca

原文對這個參數的解釋是:

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

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


下面看源代碼

接口:

[java] view plain copy
  1. private interface Account {  
  2.     public Account deposit (double value);  
  3.     public double getBalance ();  
  4. }  

Handler:

[java] view plain copy
  1. private class ExampleInvocationHandler implements InvocationHandler {  
  2.   
  3.     private double balance;  
  4.   
  5.     @Override  
  6.     public Object invoke (Object proxy, Method method, Object[] args) throws Throwable {  
  7.   
  8.         // simplified method checks, would need to check the parameter count and types too  
  9.         if ("deposit".equals(method.getName())) {  
  10.             Double value = (Double) args[0];  
  11.             System.out.println("deposit: " + value);  
  12.             balance += value;  
  13.             return proxy; // here we use the proxy to return 'this'  
  14.         }  
  15.         if ("getBalance".equals(method.getName())) {  
  16.             return balance;  
  17.         }  
  18.         return null;  
  19.     }  
  20. }  

使用:

[java] view plain copy
  1. Account account = (Account) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] {Account.class, Serializable.class},  
  2.     new ExampleInvocationHandler());  
  3.   
  4. // method chaining for the win!  
  5. account.deposit(5000).deposit(4000).deposit(-2500);  
  6. System.out.println("Balance: " + account.getBalance());  
我們看到如果返回proxy的話可以對該代理對象進行連續調用

那爲什麼不返回this,而是返回proxy對象呢?

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


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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章