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

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


          網站導航:
           
          主站蜘蛛池模板: 孝义市| 南乐县| 金堂县| 胶南市| 颍上县| 平定县| 清镇市| 额济纳旗| 平原县| 海安县| 苍梧县| 应用必备| 新密市| 金塔县| 宿州市| 左权县| 郓城县| 伊川县| 大冶市| 夏邑县| 城口县| 屯昌县| 准格尔旗| 东至县| 张家界市| 普安县| 博爱县| 淳安县| 宜阳县| 瓦房店市| 专栏| 洛浦县| 临泽县| 东港市| 临漳县| 荃湾区| 含山县| 淮阳县| 博罗县| 安福县| 阳春市|