提供一个java代码比较两个对象的差异工具类,如果对象中存储的是list,则递归比较list的差异
时间: 2024-01-22 13:21:21 浏览: 72
以下是一个比较两个对象的差异工具类。如果对象中包含List,则会递归比较List中的差异。
```java
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ObjectDiffUtil {
/**
* 比较两个对象的差异,返回差异的属性名和属性值
*
* @param oldObj 旧对象
* @param newObj 新对象
* @return 差异的属性名和属性值
*/
public static Map<String, Object[]> diff(Object oldObj, Object newObj) {
Map<String, Object[]> diffMap = new HashMap<>();
Class<?> clazz = oldObj.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
try {
Object oldValue = field.get(oldObj);
Object newValue = field.get(newObj);
if (oldValue == null && newValue == null) {
continue;
}
if (oldValue == null || !oldValue.equals(newValue)) {
if (oldValue instanceof List && newValue instanceof List) {
ListDiffResult listDiffResult = diffList((List) oldValue, (List) newValue);
diffMap.put(field.getName(), new Object[]{listDiffResult.getRemoved(), listDiffResult.getAdded()});
} else {
diffMap.put(field.getName(), new Object[]{oldValue, newValue});
}
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return diffMap;
}
/**
* 比较两个List的差异,返回差异的新增元素和删除元素
*
* @param oldList 旧List
* @param newList 新List
* @return 差异的新增元素和删除元素
*/
private static ListDiffResult diffList(List oldList, List newList) {
ListDiffResult listDiffResult = new ListDiffResult();
for (Object item : oldList) {
if (!newList.contains(item)) {
listDiffResult.getRemoved().add(item);
}
}
for (Object item : newList) {
if (!oldList.contains(item)) {
listDiffResult.getAdded().add(item);
}
}
return listDiffResult;
}
/**
* List差异结果类,包含新增元素和删除元素
*/
private static class ListDiffResult {
private List<Object> removed = new ArrayList<>();
private List<Object> added = new ArrayList<>();
public List<Object> getRemoved() {
return removed;
}
public List<Object> getAdded() {
return added;
}
}
}
```
使用示例:
```java
public class Main {
public static void main(String[] args) {
List<String> oldList = new ArrayList<>();
oldList.add("A");
oldList.add("B");
oldList.add("C");
oldList.add("D");
List<String> newList = new ArrayList<>();
newList.add("B");
newList.add("C");
newList.add("D");
newList.add("E");
Map<String, Object[]> diffMap = ObjectDiffUtil.diff(oldList, newList);
for (Map.Entry<String, Object[]> entry : diffMap.entrySet()) {
Object[] diff = entry.getValue();
System.out.println(entry.getKey() + ": removed=" + diff[0] + ", added=" + diff[1]);
}
}
}
```
输出结果:
```
removed: [A], added: [E]
```
阅读全文