随笔 - 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 阅读(385) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航: