懵懵燈燈的BLOG

          寒夜孤燈點點星

            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理 ::
            56 隨筆 :: 10 文章 :: 22 評論 :: 0 Trackbacks
           1import java.lang.reflect.InvocationHandler;
           2import java.lang.reflect.Method;
           3import java.lang.reflect.Proxy;
           4
           5
           6public class MyProxy {
           7    
           8    public static void main (String[] args){
           9        BusinessInterface businessImpl=new BusinessImpl();
          10        
          11        InvocationHandler handler = new LogHandler(businessImpl);
          12        
          13        BusinessInterface proxy= (BusinessInterface) Proxy.newProxyInstance(
          14                businessImpl.getClass().getClassLoader(),
          15                businessImpl.getClass().getInterfaces(),
          16                handler);
          17        
          18        proxy.processBusiness();
          19        
          20    }

          21}

          22
          23interface BusinessInterface{
          24    public  void processBusiness();
          25}

          26
          27class BusinessImpl implements BusinessInterface{
          28
          29    public void processBusiness() {
          30        // TODO Auto-generated method stub
          31        System.out.println("Processing business logic ");
          32    }

          33}

          34
          35class LogHandler implements InvocationHandler {
          36    
          37    private Object delegate;
          38    public LogHandler(Object delegate){
          39        this.delegate=delegate;
          40    }

          41
          42    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
          43        // TODO Auto-generated method stub
          44        Object o=null;
          45        try{
          46            System.out.println("INFO Begin ");
          47            o=method.invoke(delegate, args);
          48            System.out.println("INFO End ");
          49        }
          catch (Exception e){
          50            System.out.println("INFO Exception ");
          51        }

          52        return o;
          53    }

          54}
          這里用java.lang.reflect.Proxy實現動態代理類,在其中實現了在方法調用前和方法調用后的日志功能。
          posted on 2008-02-27 12:50 懵懵燈燈 閱讀(863) 評論(0)  編輯  收藏

          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 密云县| 长汀县| 汾阳市| 石嘴山市| 泾阳县| 忻城县| 高阳县| 沅陵县| 瑞丽市| 三原县| 大竹县| 科尔| 扶风县| 兴义市| 稻城县| 沂源县| 瑞昌市| 尚志市| 汽车| 台山市| 淳安县| 读书| 万宁市| 佳木斯市| 泰顺县| 加查县| 金坛市| 同心县| 正阳县| 巴青县| 上林县| 邢台县| 新邵县| 康乐县| 贵溪市| 建德市| 南乐县| 会昌县| 宁乡县| 红安县| 岑溪市|