懵懵燈燈的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 懵懵燈燈 閱讀(860) 評論(0)  編輯  收藏

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


          網站導航:
          博客園   IT新聞   Chat2DB   C++博客   博問  
           
          主站蜘蛛池模板: 西乡县| 灵璧县| 西吉县| 阿荣旗| 屏山县| 乌兰察布市| 桐梓县| 遵义县| 延安市| 五华县| 高唐县| 乌兰察布市| 鲁山县| 宁蒗| 九龙县| 开化县| 锡林浩特市| 平谷区| 衡东县| 白沙| 弋阳县| 隆子县| 五常市| 孟津县| 陵水| 松江区| 白朗县| 肥乡县| 无为县| 山东省| 宜春市| 沾化县| 岱山县| 济宁市| 昌乐县| 东辽县| 玛纳斯县| 易门县| 华容县| 汾西县| 吴忠市|