日志数据前后计算
public class CompareFieldUtil {
public static void fieldsEquals(List<Object> list) throws NoSuchFieldException {
Object source = list.get(0);
Object target = list.get(1);
if (source == null || target == null) {
return;
}
Class<?> sourceClass = source.getClass();
Class<?> targetClass = target.getClass();
Field[] sourceFields = source.getClass().getDeclaredFields();
Field[] targetFields = target.getClass().getDeclaredFields();
for (Field sourceField : sourceFields) {
sourceField.setAccessible(true);
String fieldName = sourceField.getName();
Field targetField = targetClass.getDeclaredField(fieldName);
targetField.setAccessible(true);
Object sourceValue = null;
Object targetValue = null;
try {
sourceValue = sourceField.get(source);
targetValue = targetField.get(target);
if (sourceValue instanceof List && targetValue instanceof List) {
List<?> coll1 = (List<?>) sourceValue;
List<?> coll2 = (List<?>) targetValue;
for (int i = 0; i < coll1.size(); i++) {
fieldsEquals(Arrays.asList(coll1.get(i), coll2.get(i)));
}
} else {
if (sourceValue == null && targetValue == null){
return;
}
if ((sourceValue != null && sourceValue.equals(targetValue)) || (targetValue != null && targetValue.equals(sourceValue))) {
targetField.set(target, null);
sourceField.set(source, null);
}
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws NoSuchFieldException {
MyClass obj1 = new MyClass();
obj1.setId(1);
obj1.setName("Test");
obj1.setItems(Arrays.asList(new Item(1, "Item1"), new Item(2, "Item2")));
MyClass obj2 = new MyClass();
obj2.setId(2);
obj2.setName("Test");
obj2.setItems(Arrays.asList(new Item(1, "Item2"), new Item(2, "Item2")));
fieldsEquals(Arrays.asList(obj1, obj2));
System.out.println("obj1: " + JSON.toJSONString(obj1) + "obj2: " + JSON.toJSONString(obj2));
}
@Data
static class MyClass {
private Integer id;
private String name;
private List<Item> items;
}
@Data
@AllArgsConstructor
static class Item {
private Integer id;
private String name;
}
}