方式1:
使用json的反序列化来实现转换,TypeReference可以明确的指定反序列化的类型
JSON.parseObject(JSON.toJSONString(object),new TypeReference<Map<String,Object>>(){});
方式2:
使用反射
public static Map<String, Object> convertBeanToMap(Object object)
{
if(object == null){
return null;
}
Map<String, Object> map = new HashMap<>();
try {
BeanInfo beanInfo = Introspector.getBeanInfo(object.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
if (!key.equals("class")) {
Method getter = property.getReadMethod();
Object value = getter.invoke(object);
map.put(key, value);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}