隨筆-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 閱讀(1919) 評論(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 不同實現 +反射都好用的多  回復  更多評論
            

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


          網站導航:
           
          主站蜘蛛池模板: 夏津县| 萨迦县| 淮北市| 石门县| 称多县| 博乐市| 张家口市| 南阳市| 湘乡市| 贞丰县| 石阡县| 淅川县| 克什克腾旗| 五台县| 资阳市| 团风县| 牙克石市| 垫江县| 丹东市| 武冈市| 三穗县| 时尚| 安徽省| 芒康县| 维西| 东丽区| 东至县| 谷城县| 监利县| 青海省| 拜城县| 昌吉市| 石嘴山市| 高邑县| 左贡县| 营山县| 繁昌县| 青龙| 康定县| 平湖市| 玉屏|