1. 代码示例:
直接复制粘贴就可以使用
/**
* map处理工具类
*
* @author colin
*/
public class MapUtil {
/**
* 将Java实体对象转换为Map对象
*
* @param object Java实体对象
* @return Map对象
* @throws Exception 异常信息
*/
public static Map<String, Object> objectToMap(Object object) throws Exception {
if (object == null) {
return null;
}
Map<String, Object> map = new HashMap<String, Object>();
BeanInfo beanInfo = Introspector.getBeanInfo(object.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
String key = propertyDescriptor.getName();
if (!"class".equals(key)) {
Method getter = propertyDescriptor.getReadMethod();
Object value = getter.invoke(object);
map.put(key, value);
}
}
return map;
}
}
非常简单的工具类代码就结束了,希望可以帮到大家
🐧 🐧 :1745957645