java动态代理实例

引用:http://www.blogjava.net/thisliy/archive/2009/10/24/299621.html

 

1.真实对象接口

1  public   interface  IAnimal {
2       void  info();
3  }


2.真实类

1  public   class  Cat  implements  IAnimal{
2 
3       public   void  info() {
4          System.out.println( " This is a cat! " );
5      }
6 
7  }


3.调用处理器

 1  import  java.lang.reflect.InvocationHandler;
 2  import  java.lang.reflect.Method;
 3 
 4  public   class  TraceHandler  implements  InvocationHandler{
 5      
 6       private  Object target; // 以真实角色作为代理角色的属性
 7      
 8       // 构造器
 9       public  TraceHandler(Object target) {   
10           this .target  =  target;   
11      }   
12 
13       /*
14       * 通过反射机制动态执行真实角色的每一个方法
15        */
16       public  Object invoke(Object proxy, Method method, Object[] args)
17               throws  Throwable {
18           try  {
19              System.out.println( " 被拦截的方法: "   +  method.getName()); 
20              System.out.println( " 预处理. " );
21              
22               return  method.invoke(target, args); // 调用真是对象的method方法
23              
24          }  catch  (Exception e) {
25               return   null ;
26          }  finally  {
27               System.out.println( " 善后处理. " );
28          }
29      }
30  }


4.客户端

 1  import  java.lang.reflect.InvocationHandler;
 2  import  java.lang.reflect.Proxy;
 3 
 4  public   class  ProxyTest {
 5       public   static   void  main(String[] args) {
 6          
 7           // 真实对象(即被代理对象)
 8           final  IAnimal animal  =   new  Cat();
 9          
10           // 为真实对象制定一个调用处理器
11          InvocationHandler handler  =   new  TraceHandler(animal);
12          
13           // 获得真实对象(animal)的一个代理类 ★★★★★
14          Object proxyObj  =  Proxy.newProxyInstance(
15                  animal.getClass().getClassLoader(),  // 真实对象的类加载器
16                  animal.getClass().getInterfaces(),   // 真实对象实现的所有接口
17                  handler                                 // 真实对象的处理器
18                  );
19           
20            if  (proxyObj  instanceof  IAnimal) {
21              System.out.println( " the proxyObj is an animal! " );
22              
23              IAnimal animalProxy  =  (IAnimal)proxyObj; // proxyObj与animal都实现了IAnimal接口
24              
25              animalProxy.info(); // 像普通animal对象一样使用(通过handler的invoke方法执行)
26          }  else  {
27              System.out.println( " the proxyObj isn't an animal! " );
28          }
29      }
30  }

 

结果:

the proxyObj is an animal!
被拦截的方法:info
预处理.
This is a cat!
善后处理.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值