隨筆 - 32, 文章 - 1, 評論 - 5, 引用 - 0
          數據加載中……

          利用反射打印測試JavaBean

          /**
            * 測試方法
            *
            * @param obj
            * @return
            */
           public static StringBuffer testPOJO(Object obj) {
            Class cls = obj.getClass();
            Field[] fields = cls.getDeclaredFields();
            StringBuffer resultBuf = new StringBuffer();
            try {
             for (int i = 0; i < fields.length; i++) {
              String fieldName = fields[i].getName();
              Class fieldType = fields[i].getType();
              Method method;
              if (fieldType.equals(boolean.class)) {
               method = cls.getMethod("is" + genMethodName(fieldName));
              } else {
               method = cls.getMethod("get" + genMethodName(fieldName));
              }
              Object res;
              if ((res = method.invoke(obj)) != null) {
               String result = res.toString();
               resultBuf.append("[" + fieldName + "] = " + result + "\n");
              } else {
               resultBuf.append("[" + fieldName + "] = NULL \n");
              }
             }
            } catch (Exception e) {
             e.printStackTrace();
            }
            return resultBuf;
           }
           
           public static String genMethodName(String fieldName) {
            String firstWord = fieldName.substring(0, 1);
            String others = fieldName.substring(1, fieldName.length());
            return firstWord.toUpperCase() + others;
           }

          posted on 2011-10-12 16:34 colorfire 閱讀(396) 評論(0)  編輯  收藏


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


          網站導航:
           
          主站蜘蛛池模板: 绍兴市| 高平市| 多伦县| 绥棱县| 子洲县| 稷山县| 荆州市| 肥乡县| 双峰县| 右玉县| 东城区| 永年县| 巴彦淖尔市| 新营市| 洪洞县| 巴马| 云龙县| 苏尼特右旗| 龙岩市| 长乐市| 金平| 巴青县| 邵阳县| 临江市| 孟村| 安岳县| 扎鲁特旗| 岫岩| 赣榆县| 海南省| 林甸县| 黔东| 于都县| 德格县| 卓尼县| 太仓市| 金寨县| 瑞金市| 南阳市| 顺昌县| 江山市|