/**
* 对比两个对象的值是否有差异
* @param source 对象1
* @param target 对象2
* @param isInclude 属性集合是发需要包含对象字段
* @param fields 属性集合
* @param <T>
* @return
*/
public static <T> Map<String, Object> compareBean(T source, T target, boolean isInclude, String... fields) {
Map<String, Object> sourceMap = BeanUtil.beanToMap(source);
Map<String, Object> targetMap = BeanUtil.beanToMap(target);
Map<String, Object> resultMap = new HashMap<>(16);
for (Map.Entry<String, Object> entry : sourceMap.entrySet()) {
if (ArrayUtil.isNotEmpty(fields)) {
if (isInclude && !ArrayUtil.contains(fields, entry.getKey())) {
continue;
}
if (!isInclude && ArrayUtil.contains(fields, entry.getKey())) {
continue;
}
}
Object oldVal = entry.getValue();
Object newVal = targetMap.get(entry.getKey());
boolean isOldAndNewBlank = (oldVal == null || (oldVal instanceof String && StringUtils.isBlank((String) oldVal)))
&& (newVal == null || (newVal instanceof String && StringUtils.isBlank((String) newVal)));
if (isOldAndNewBlank) {
continue;
}
if (!Objects.equals(oldVal, newVal)) {
resultMap.put(entry.getKey(), String.format("oldVal:%s, newVal:%s", oldVal, newVal));
}
}
return resultMap;
}
java对比两个对象的值是否有差异(比较相同属性名的字段)
于 2023-09-21 10:12:05 首次发布