package com.opensesame.tms.core.util;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
public class CompareUtils {
public static boolean compareBean(Object obj1, Object obj2) {
try {
if (obj1.getClass() != obj2.getClass()) {
return false;
} else {
Class claz = obj1.getClass();
PropertyDescriptor[] pds = Introspector.getBeanInfo(claz, Object.class).getPropertyDescriptors();
for (PropertyDescriptor pd : pds) {
Method readMethod = pd.getReadMethod();
Object o1 = readMethod.invoke(obj1);
Object o2 = readMethod.invoke(obj2);
if (Objects.isNull(o1) && Objects.isNull(o2)) {
continue;
}
if (null == o1 || null == o2) {
return false;
}
if (!compareField(o1, o2)) {
return false;
}
}
return true;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public static <T extends Comparable<T>> boolean compareList(List<T> list1, List<T> list2) {
if (list1.size() != list2.size()) {
return false;
}
Collections.sort(list1);
Collections.sort(list2);
for (int i = 0; i < list1.size(); i++) {
if (!compareBean(list1.get(i), list2.get(i))) {
return false;
}
}
return true;
}
private static boolean compareField(Object o1, Object o2) {
Boolean sign = false;
Object ot = null;
if (!Objects.isNull(o1)) {
ot = o1;
} else if (!Objects.isNull(o2)) {
ot = o2;
}
if (ot instanceof String) {
sign = !o1.equals(o2);
} else if (ot instanceof BigDecimal) {
sign = ((BigDecimal) o1).compareTo((BigDecimal) o2) != 0;
} else if (ot instanceof Integer) {
sign = ((Integer) o1).compareTo((Integer) o2) != 0;
} else if (ot instanceof Boolean) {
sign = ((Boolean) o1).compareTo((Boolean) o2) != 0;
} else if (ot instanceof Long) {
sign = ((Long) o1).compareTo((Long) o2) != 0;
}
return sign;
}
}