Object Bean 转为 map

来源:互联网 发布:专业软件 编辑:程序博客网 时间:2024/06/05 16:38

简述:

将一个Bean对象转为map, 只转换一层嵌套的实现


实现:

/** * 将object 转换为map对象 * @param bean * @return * @throws IntrospectionException  * @throws InvocationTargetException  * @throws IllegalArgumentException  * @throws IllegalAccessException  */public static Map objectToMap(Object bean) throws IntrospectionException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {Map map = new HashMap<String, Object>();BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();  for (PropertyDescriptor property : propertyDescriptors) {  String key = property.getName();  // 得到property对应的getter方法  Method getter = property.getReadMethod();Object value = getter.invoke(bean);map.put(key, value);}  return map;}


0 0