/**
* 利用Introspector和PropertyDescriptor:属性描述器 将Bean --> Map
* @param obj 实体类
* @return
*/
public static Map<String, Object> transBean2Map(Object obj) {
if (obj == null) {
return null;
}
Map<String, Object> map = new HashMap<String, Object>();
try {
//利用java反射转为BeanInfo
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
// PropertyDescriptor:属性描述器
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
// 过滤class属性
if (!key.equals("class")) {
// 得到property对应的getter方法
Method getter = property.getReadMethod();
Object value = getter.invoke(obj);
map.put(key, value);
}
}
} catch (Exception e) {
log.error("transBeanMap Error {}" ,e);
}
return map;
}
实体类转map方法
于 2022-03-02 13:59:31 首次发布
该博客介绍了一种使用Java Introspector和PropertyDescriptor将Bean对象转换为Map的方法。通过反射获取Bean的BeanInfo,然后遍历PropertyDescriptors,过滤掉class属性,调用getter方法获取每个属性的值,并存入Map中。此过程适用于需要将Java Bean对象转化为Map进行操作的场景。
936

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



