@Slf4j
public class MapUtil {
private static BiConsumer<Map<String, String>, String> saveNullField = (map, key) -> map.put(key, null);
private static BiConsumer<Map<String, String>, String> ignoreNullField = (map, key) -> {
};
/**
* bean转成map,保留值=null字段
*/
public static Map<String, String> toMapWithNullField(Object obj) {
return toMap(obj, saveNullField);
}
/**
* bean转成map,丢弃值=null字段
*/
public static Map<String, String> toMapWithOutNullField(Object obj) {
return toMap(obj, ignoreNullField);
}
private static Map<String, String> toMap(Object obj, BiConsumer<Map<String, String>, String> biConsumer) {
if (obj == null) {
return Maps.newHashMap();
}
Map<String, String> fieldMap = new HashMap<>(10);
try {
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
if (!"class".equalsIgnoreCase(key)) {
Method getter = property.getReadMethod();
Object value = getter.invoke(obj);
if (value != null) {
fieldMap.put(key, String.valueOf(value));
} else {
biConsumer.accept(fieldMap, key);
}
}
}
return fieldMap;
} catch (Exception e) {
log.error("[MapUtil] bean to map error:", e);
}
return Maps.newHashMap();
}
}
MapUtil
最新推荐文章于 2024-04-17 14:30:47 发布