import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;
public class CompareBeanUtil {
public static List<Comparision> comparisionObjList(String compareBase, List<Object> beforeObjs, List<Object> afterObjs, String module) throws Exception {
if (beforeObjs == null && afterObjs == null) throw new Exception("两个对比对象链表不能同时为空");
List<Comparision> differents = new ArrayList<Comparision>();
Map<String, Object> beforeMap = new HashMap<>();
Map<String, Object> afterMap = new HashMap<>();
Set<String> sameSet = new HashSet<>();
Set<String> beforeOnlySet = new HashSet<>();
Set<String> afterOnlySet = new HashSet<>();
for (Object a : beforeObjs) {
String fiName = getFieldValueByFieldName(compareBase, a);
beforeMap.put(fiName, a);
beforeOnlySet.add(fiName);
}
for (Object b : afterObjs) {
String fiName = getFieldValueByFieldName(compareBase, b);
afterMap.put(fiName, b);
afterOnlySet.add(fiName);
}
// beforeOnlySet和afterOnlySet交集
sameSet.addAll(beforeOnlySet);
sameSet.retainAll(afterOnlySet);
// beforeOnlySet-sameSet的差集
beforeOnlySet.removeAll(sameSet);
// afterOnlySet-sameSet的差集
afterOnlySet.removeAll(sameSet);
for (String co : sameSet) {
differents.addAll(compareObj(beforeMap.get(co), afterMap.get(co), module, compareBase));
}
for (String co : beforeOnlySet) {
differents.addAll(compareObj(beforeMap.get(co), beforeMap.get(co).getClass().newInstance(), module, compareBase));
}
for (String co : afterOnlySet) {
differents.addAll(compareObj(afterMap.get(co).getClass().newInstance(), afterMap.get(co), module, compareBase));
}
return differents;
}
/**
* 根据属性名获取属性值
*
* @param fieldName
* @param object
* @return
*/
public static String getFieldValueByFieldName(String fieldName, Object object) {
try {
Field field = object.getClass().getDeclaredField(fieldName);
//设置对象的访问权限,保证对private的属性的访问
field.setAccessible(true);
return (String) (field.get(object) + "");//+“” 为了兼容int 瑕疵是null会转换为0
} catch (Exception e) {
return null;
}
}
/**
* 比较对象不同
*
* @param beforeObj
* @param afterObj
* @param module
* @param compareBase
* @return List<Comparision>
*/
public static List<Comparision> compareObj(Object beforeObj, Object afterObj, String module, String compareBase) throws Exception {
List<Comparision> differents = new ArrayList<Comparision>();
if (beforeObj == null) throw new Exception("原对象不能为空");
if (afterObj == null) throw new Exception("新对象不能为空");
if (!beforeObj.getClass().isAssignableFrom(afterObj.getClass())) {
throw new Exception("两个对象不相同,无法比较");
}
//取出属性
Field[] beforeFields = beforeObj.getClass().getDeclaredFields();
Field[] afterFields = afterObj.getClass().getDeclaredFields();
Field.setAccessible(beforeFields, true);
Field.setAccessible(afterFields, true);
Object keyWord = null;
if (module.equals("QS") || module.equals("HP") || module.equals("GG")|| module.equals("YSL")) {
Field trName = Arrays.stream(beforeFields).filter(field -> field.getName().equals(compareBase)).findFirst().orElse(null);
if (trName != null) {
keyWord = trName.get(beforeObj);
}
}
//遍历取出差异值
if (beforeFields != null && beforeFields.length > 0) {
for (int i = 0; i < beforeFields.length; i++) {
Object beforeValue = beforeFields[i].get(beforeObj);
Object afterValue = afterFields[i].get(afterObj);
if ((beforeValue != null && !"".equals(beforeValue) && !beforeValue.equals(afterValue)) ||
((beforeValue == null || "".equals(beforeValue)) && afterValue != null)) {
Comparision comparison = new Comparision();
String name = beforeFields[i].getName();
comparison.setField(transfer2Chinese(module, name, keyWord, comparison));
comparison.setBefore(beforeValue);
comparison.setAfter(afterValue);
differents.add(comparison);
}
}
}
return differents;
}
/**
* 将英文转义中文
*
* @param module
* @param name
* @param keyWord
* @param comparison
* @return String
*/
private static String transfer2Chinese(String module, String name, Object keyWord, Comparision comparison) {
if (module.equals("QS")) {
comparison.setKeyword(keyWord);
switch (name) {
case "flow":
return "流量(m³/s)";
case "wl":
return "水位(m)";
default:
return name;
}
}
if (module.equals("HP")) {
comparison.setKeyword(keyWord);
switch (name) {
case "val":
return "当日补水量(万m³)";
case "valTotal":
return "累计补水量(万m³)";
default:
return name;
}
}
if (module.equals("GG")) {
comparison.setKeyword(keyWord);
switch (name) {
case "val":
return "灌溉进度";
default:
return name;
}
}
if (module.equals("YSL")) {
comparison.setKeyword(keyWord);
switch (name) {
case "farmValue":
return "农业用水";
case "industryValue":
return "工业用水";
case "livingValue":
return "生活用水";
default:
return name;
}
}
return name;
}
/**
* 根据模块对差异集转成字符串
*
* @param compareBase
* @param preList
* @param afterList
* @param module
* @param time
* @return String
*/
public static String CompareListByModule(String compareBase, List<Object> preList, List<Object> afterList, String module, String time) {
try {
List<Comparision> comparisions = CompareBeanUtil.comparisionObjList(compareBase, preList, afterList, module);
StringBuffer stringBuffer = new StringBuffer();
if (!CollectionUtils.isEmpty(comparisions)) {
if (StringUtils.hasLength(time)) {
stringBuffer.append("数据日期:")
.append(time)
.append(";");
}
Map<Object, List<Comparision>> objectListMap = comparisions.stream().collect(Collectors.groupingBy(Comparision::getKeyword));
for (Map.Entry<Object, List<Comparision>> objectListEntry : objectListMap.entrySet()) {
List<Comparision> comparisionList = objectListEntry.getValue();
for (Comparision comparision : comparisionList) {
stringBuffer.append(objectListEntry.getKey())
.append(comparision.getField())
.append(",原值:")
.append(comparision.getBefore())
.append(",新值:")
.append(comparision.getAfter())
.append(";");
}
}
return stringBuffer.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public static <T> List<Object> transJson2List2(JSONArray data, Class<T> clazz) {
List<Object> list = new ArrayList<Object>();
for (int i = 0; i < data.size(); i++) {
JSONObject jsonObject = data.getJSONObject(i);
T o;
try {
o = (T) Class.forName(clazz.getName()).newInstance();
Field[] fields = clazz.getDeclaredFields();
Field.setAccessible(fields, true);
if (fields != null && fields.length > 0) {
Field farmValue=null;
Field industryValue=null;
Field livingValue=null;
for (Field field : fields) {
switch (field.getName()) {
case "srName":
field.set(o, jsonObject.get(field.getName()));
break;
case "farmValue":
farmValue=field;
break;
case "industryValue":
industryValue=field;
break;
case "livingValue":
livingValue=field;
break;
default:
break;
}
}
for (Field field : fields) {
if (field.getName().equals("irrDatas")) {
JSONArray jsonArray = (JSONArray) jsonObject.get(field.getName());
for (int j = 0; j < jsonArray.size(); j++) {
JSONObject innerJsonObject = jsonArray.getJSONObject(j);
switch ((String)innerJsonObject.get("trIrrName")) {
case "生活用水":
livingValue.set(o, innerJsonObject.get("val"));
break;
case "工业用水":
industryValue.set(o, innerJsonObject.get("val"));
break;
case "农业用水":
farmValue.set(o, innerJsonObject.get("val"));
break;
default:
break;
}
}
}
}
}
list.add(o);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return list;
}
public static void main(String[] args) {
Date date = new Date();
List<Object> oldList = new ArrayList<>();
List<Object> newList = new ArrayList<>();
MainCanal oldwf1 = new MainCanal(105276, 1, "河西总干渠", 1, 10);
MainCanal oldwf2 = new MainCanal(105278, 3, "潜坝", null, 20);
MainCanal oldwf3 = new MainCanal(105286, 36, "总干渠直开口", 1, 20);
oldList.add(oldwf1);
oldList.add(oldwf2);
oldList.add(oldwf3);
MainCanal newwf1 = new MainCanal(105276, 1, "河西总干渠", 13, 20);
MainCanal newwf2 = new MainCanal(105278, 3, "潜坝", null, 20);
MainCanal newwf3 = new MainCanal(105286, 36, "总干渠直开口", 12, 25);
newList.add(newwf1);
newList.add(newwf2);
newList.add(newwf3);
try {
List<Comparision> comparisions = comparisionObjList("trName", oldList, newList, "QS");
StringBuilder stringBuilder = new StringBuilder();
if (!CollectionUtils.isEmpty(comparisions)) {
Map<Object, List<Comparision>> objectListMap = comparisions.stream().collect(Collectors.groupingBy(Comparision::getKeyword));
for (Map.Entry<Object, List<Comparision>> objectListEntry : objectListMap.entrySet()) {
List<Comparision> comparisionList = objectListEntry.getValue();
for (Comparision comparision : comparisionList) {
stringBuilder.append(objectListEntry.getKey())
.append(comparision.getField())
.append(",原值:")
.append(comparision.getBefore())
.append(",新值:")
.append(comparision.getAfter())
.append(";");
}
}
System.out.println(stringBuilder.toString());
}
System.out.println(JSON.toJSONString(comparisionObjList("trName", oldList, newList, "QS")));
} catch (Exception e) {
System.out.println(e);
}
}
}
public class Comparision {
//字段
private String Field;
//字段旧值
private Object before;
//字段新值
private Object after;
private Object keyword;
public Object getKeyword() {
return keyword;
}
public void setKeyword(Object keyword) {
this.keyword = keyword;
}
public String getField() {
return Field;
}
public void setField(String field) {
Field = field;
}
public Object getBefore() {
return before;
}
public void setBefore(Object before) {
this.before = before;
}
public Object getAfter() {
return after;
}
public void setAfter(Object after) {
this.after = after;
}
}
import lombok.Data;
@Data
public class MainCanal {
private long id;
private int trId;
private String trName;
private Integer flow;
private Integer wl;
public MainCanal() {
}
public MainCanal(long id, int trId, String trName, Integer flow, Integer wl) {
this.id = id;
this.trId = trId;
this.trName = trName;
this.flow = flow;
this.wl = wl;
}
}