java对象转map
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class MapUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(MapUtil.class);
public static Map<String, Object> beanToMap(Object beanObj) {
Map<String, Object> map = new HashMap<>();
if (Objects.nonNull(beanObj)) {
try {
BeanInfo beanInfo = Introspector.getBeanInfo(beanObj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
if (!StringUtils.equals(key, "class")) {
Method getter = property.getReadMethod();
Object value = getter != null ? getter.invoke(beanObj) : null;
map.put(key, value);
}
}
} catch (Exception ex) {
LOGGER.error(String.format("java对象转map转换发生异常:%s", ex.getMessage()));
throw new RuntimeException(ex);
}
}
return map;
}
}