隨筆-55  評論-208  文章-0  trackbacks-0
          問題是這樣的,我看到原來有一個方法是根據name的名稱調用getName()這個方法。
          然后方法的實現是使用字符串的判斷來實現的
          代碼如下:
          public Object getOrderby() {
                  
          if (ORDER_TITLE.equals(this.ordered)) {
                      
          return getTitle();
                  }
           else if (ORDER_RENDERDATE.equals(this.ordered)) {
                      
          return getRenderDate();
                  }
           else if (ORDER_CREATEDATE.equals(this.ordered)) {
                      
          return getCreateDate();
                  }
           else if (ORDER_LASTMODIFIED.equals(this.ordered)) {
                      
          return getLastModified();
                  }
           else {
                      
          return getTitle();
                  }

              }

          這樣的話如果以后新增get方法就意味著要增加這個getOrderby()方法的判斷。
          所以我決定用類反射來改造這個方法,首先定義一個doGetMethod的方法
           private Object doGetMethod(String methodName) throws Exception {
                  Object result 
          = null;
                  Object[] eo 
          = new Object[] {};
                  String getMethodName 
          = "get" + methodName.toLowerCase();
                  Method[] methods 
          = getClass().getMethods();
                  
          for (int i = 0; i < methods.length; i++{
                      Method method 
          = methods[i];
                      
          if (getMethodName.equals(method.getName().toLowerCase())) {
                          result 
          = method.invoke(this, eo);
                      }

                  }

                  
          return result;
              }
          這里根據methodName組合成getMethodName,然后到Method[]中找這個Method,然后用invoke調用這個方法
          這里要說明invoke這個方法的參數是第一個參數是指定包含方法的類,第二個參數是指定方法需要的參數。
          最后修改原來的getOrderBy
            public Object getOrderby() {
                  Object obj 
          = getTitle();
                  
          try {
                      obj 
          = doGetMethod(getOrdered());
                  }
           catch (Exception e) {
                      
          return obj;
                  }

                  
          return obj;
              }
          posted on 2007-04-12 15:36 rocket 閱讀(1924) 評論(3)  編輯  收藏

          評論:
          # re: 根據name調用getName方法 2007-04-12 17:36 | G_G
          沙發
            回復  更多評論
            
          # re: 根據name調用getName方法 2007-04-12 17:38 | popoer
          good!  回復  更多評論
            
          # re: 根據name調用getName方法 2007-04-12 19:57 | 劉甘泉
          把簡單的東西弄復雜了,如果方法固定的話 用 if else 效果更好,如果需要隨時更改的話,用interface 不同實現 +反射都好用的多  回復  更多評論
            

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


          網站導航:
           
          主站蜘蛛池模板: 凤庆县| 山阳县| 壤塘县| 蒙阴县| 遵义县| 巴彦淖尔市| 沁阳市| 五莲县| 礼泉县| 阿城市| 万盛区| 淳安县| 澄迈县| 克山县| 寻乌县| 景德镇市| 宁蒗| 佛山市| 工布江达县| 台安县| 神农架林区| 泾源县| 吐鲁番市| 通河县| 苗栗市| 赞皇县| 桑日县| 龙口市| 麦盖提县| 绍兴县| 称多县| 柯坪县| 哈巴河县| 房山区| 阳谷县| 瓮安县| 吉安市| 渝北区| 白沙| 江油市| 墨玉县|