zoukankan      html  css  js  c++  java
  • InvocationHandler中invoke方法中的第一个参数proxy的用途

    最近在研究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。

  • 相关阅读:
    数据库系统学习(九)-嵌入式SQL语言之基本技巧
    操作系统学习(九)-- 操作系统之文件系统(目录)
    操作系统学习(八)-- 操作系统之磁盘(调度)与文件(实现)
    从windows server 2003中学到的事儿
    一名游戏开发者的告白
    所谓“学术境界”
    java解惑
    程序员的职业素养
    行业大会_平台
    寻找优秀的程序员
  • 原文地址:https://www.cnblogs.com/zhaoxinshanwei/p/8604350.html
Copyright © 2011-2022 走看看