zoukankan      html  css  js  c++  java
  • 动态代理

    1 public interface UserManager {
    2     public void addUser(String name);
    3 }
    1 public class UserManagerImpl implements UserManager {
    2 
    3     @Override
    4     public void addUser(String name) {
    5 
    6         System.out.println(" Add   User  " + name);
    7     }
    8 
    9 }

     InvocationHandler

     1 /**
     2  * 实现自己的InvocationHandler
     3  * 
     4  * @author zyb
     5  * @since 2012-8-9
     6  * 
     7  */
     8 public class MyInvocationHandler implements InvocationHandler {
     9 
    10     // 目标对象
    11     private Object target;
    12 
    13     /**
    14      * 构造方法
    15      * 
    16      * @param target
    17      *            目标对象
    18      */
    19     public MyInvocationHandler(Object target) {
    20         super();
    21         this.target = target;
    22     }
    23 
    24     /**
    25      * 执行目标对象的方法
    26      */
    27     public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    28 
    29         // 执行目标对象的方法
    30         Object result = null;
    31         try {
    32             // 在目标对象的方法执行之前简单的打印一下
    33             System.out.println("------------------before------------------");
    34 
    35             result = method.invoke(target, args);
    36 
    37             // 在目标对象的方法执行之后简单的打印一下
    38             System.out.println("-------------------after------------------");
    39         } catch (Exception e) {
    40             // TODO Auto-generated catch block
    41             e.printStackTrace();
    42         }
    43 
    44         return result;
    45     }
    46 
    47 }

     测试:

     1 public class Client {
     2     public static void main(String[] args) {
     3     
     4                UserManager userManager = new UserManagerImpl();
     5        
     6        // 实例化InvocationHandler  
     7        MyInvocationHandler invocationHandler = new MyInvocationHandler(userManager);          
     8        // 根据目标对象生成代理对象   
     9          UserManager userManagerProxy =(UserManager) Proxy.newProxyInstance(userManager.getClass().getClassLoader(),userManager.getClass().getInterfaces(),invocationHandler);
    10          // 调用代理对象的方法  
    11          userManagerProxy.addUser(" zhangsan");
    12         
    13         
    14     }
    15 
    16 }

     结果:

    ------------------before------------------
     Add   User   zhangsan
    -------------------after------------------
  • 相关阅读:
    EF中的EntityState几个状态的说明
    sql server 更新表,每天的数据分固定批次设置批次号sql
    bootstrap Validators
    马老师 生产环境mysql主从复制、架构优化方案
    PHP在微博优化中的“大显身手”
    将form表单转化为json数据
    免费资源库收集
    奇怪的php问题
    PHP 大数自动转换为科学计数法
    access database in a helper function ?
  • 原文地址:https://www.cnblogs.com/the-wang/p/8608036.html
Copyright © 2011-2022 走看看