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 {
/**
* 比较两个对象属性值
*
* @param obj1 进行属性比较的对象1
* @param obj2 进行属性比较的对象2
* @return
*/
public static boolean compareBean(Object obj1, Object obj2) {
try {
// 只有两个对象都是同一类型的才有可比性
if (obj1.getClass() != obj2.getClass()) {
return false;
} else {
Class claz = obj1.getClass();
// 获取object的属性描述
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;
}
}
/**
* 比较两个List的所有对象属性值
*
* @param list1 进行属性比较的list1
* @param list2 进行属性比较的list2
* @return
*/
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;
}
}
对象、集合比较工具类
最新推荐文章于 2024-08-16 23:08:28 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)