public static Map convertBean(Object bean) throws IntrospectionException,
IllegalAccessException, InvocationTargetException {
Map returnMap = new HashMap();
Class type = bean.getClass(); // 获得对象的名字
BeanInfo beanInfo = Introspector.getBeanInfo(type);
// 在 Java Bean 上进行内省,了解其所有属性、公开的方法和事件
PropertyDescriptor[] propertyDescriptors = beanInfo .getPropertyDescriptors();
// 获得 beans PropertyDescriptor
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, "");
}
}
}
return returnMap;
}
}
本文介绍了一种将Java对象转换为Map的高效方法,通过使用Java反射API实现对象属性到Map键值对的映射。适用于快速获取对象属性的场景。
844

被折叠的 条评论
为什么被折叠?



