/**
* 将一个 JavaBean 对象转化为一个 Map
*
* @param bean
* 要转化的JavaBean 对象
* @return 转化出来的 Map 对象
* @throws IntrospectionException
* 如果分析类属性失败
* @throws IllegalAccessException
* 如果实例化 JavaBean 失败
* @throws InvocationTargetException
* 如果调用属性的 setter 方法失败
*/
public static Map<String, Object> convertBean(Object bean) {
Class<? extends Object> type = bean.getClass();
Map<String, Object> returnMap = new HashMap<>();
BeanInfo beanInfo;
try {
beanInfo = Introspector.getBeanInfo(type);
PropertyDescriptor[] propertyDescriptors = beanInfo
.getPropertyDescriptors();
for (int i = 0; i < propertyDescriptors.length; i++) {
PropertyDescriptor descriptor = propertyDescriptors[i];
String propertyName = descriptor.getName();
if (!propertyName.equals("class")) {
Method readMethod = descriptor.getReadMethod();
Object result = readMethod.invoke(bean, new Object[0]);
if (result != null) {
returnMap.put(propertyName, result);
} else {
returnMap.put(propertyName, "");
}
}
}
} catch (Exception e) {
log.error("Object转换成Map异常!", e);
}
return returnMap;
}
将一个javabean对象转换为map
最新推荐文章于 2024-07-31 04:31:57 发布