将javabean转换成Map

论坛 期权论坛 脚本     
匿名技术用户   2021-1-2 09:36   11   0

public static Map<String, Object> getparamsToIndex(Object obj) {
  Map<String, Object> params = new HashMap<String, Object>(0);
  try {
   PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
   PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(obj);
   for (int i = 0; i < descriptors.length; i++) {
    String name = descriptors[i].getName();
    if (!StringUtils.equals(name, "class")) {
     params.put(propertyToField(name), propertyUtilsBean.getNestedProperty(obj, name));
    }
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  return params;
 }
/**
  * 对象属性转换为字段  例如:userName to user_name
  * @param property 字段名
  * @return
  */
 public static String propertyToField(String property) {
  if (null == property) {
   return "";
  }
  char[] chars = property.toCharArray();
  StringBuffer sb = new StringBuffer();
  for (char c : chars) {
   if (CharUtils.isAsciiAlphaUpper(c)) {
    sb.append("_" + StringUtils.lowerCase(CharUtils.toString(c)));
   } else {
    sb.append(c);
   }
  }
  return sb.toString();
 }

 /**
  * 字段转换成对象属性 例如:user_name to userName
  * @param field
  * @return
  */
 public static String fieldToProperty(String field) {
  if (null == field) {
   return "";
  }
  char[] chars = field.toCharArray();
  StringBuffer sb = new StringBuffer();
  for (int i = 0; i < chars.length; i++) {
   char c = chars[i];
   if (c == '_') {
    int j = i + 1;
    if (j < chars.length) {
     sb.append(StringUtils.upperCase(CharUtils.toString(chars[j])));
     i++;
    }
   } else {
    sb.append(c);
   }
  }
  return sb.toString();
 }
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP