编程语言
首页 > 编程语言> > JavaBean对象转化成Map对象

JavaBean对象转化成Map对象

作者:互联网

/**
* JavaBean对象转化成Map对象
*
* @param javaBean
* @return
* @author
*/
public static Map<String, Object> bean2Map(Object javaBean) {
  Map<String, Object> map = new HashMap<String, Object>();

  try {
    // 获取javaBean属性
    BeanInfo beanInfo = Introspector.getBeanInfo(javaBean.getClass());

    PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    if (propertyDescriptors != null && propertyDescriptors.length > 0) {
      String propertyName = null; // javaBean属性名
      Object propertyValue = null; // javaBean属性值
      for (PropertyDescriptor pd : propertyDescriptors) {
        propertyName = pd.getName();
        if (!propertyName.equals("class")) {
          Method readMethod = pd.getReadMethod();
          propertyValue = readMethod.invoke(javaBean, new Object[0]);

          map.put(propertyName, propertyValue);
        }
      }
    }
  } catch (Exception e) {
    e.printStackTrace();
  }

  return map;
}

标签:Map,对象,propertyName,Object,propertyDescriptors,JavaBean,null,javaBean
来源: https://www.cnblogs.com/baimj/p/14108129.html