首先创建一个映射差异项的实体类存放 对比字段和对比结果
下面是对比代码 修改一下所要对比的对象和对比完返回的数据即可
/** * 获取差异项 */ private FinanceOrganizationCompare compareMainWithMinor(FinanceOrganizationNew main, FinanceOrganizationNew minor) throws ServiceException { FinanceOrganizationCompare compareResult = new FinanceOrganizationCompare(); //CompareWithApiResult compare = new CompareWithApiResult(); PropertyDescriptor[] fields = BeanUtils.getPropertyDescriptors(main.getClass()); int diffCount = 0; try { for (PropertyDescriptor field : fields) { Method readMethod = field.getReadMethod(); Object mainObj = readMethod.invoke(main); Object minorObj = readMethod.invoke(minor); if (isIgnore(field)) { continue; } boolean isSame = (mainObj == null && minor == null) || (mainObj != null && mainObj.equals(minorObj)); CompareWithApiResult result = new CompareWithApiResult(); if (!isSame && !field.getName().equals("organizationId")) { diffCount++; //result.setEqual(isSame); } if (field.getPropertyType() == Date.class) { result.setRecommend(mainObj == null ? null : DateFormatUtils.format((Date) mainObj, "yyyy/MM/dd")); result.setSource(minorObj == null ? null : DateFormatUtils.format((Date) minorObj, "yyyy/MM/dd")); } else { result.setRecommend(mainObj == null ? null : mainObj.toString()); result.setSource(minorObj == null ? null : minorObj.toString()); } if (field.getName().equals("organizationId")){ result.setFieldCode(field.getName()); result.setFieldName(EnumExcelField.getFieldValueNameByFieldValue(field.getName() != null ? field.getName() : "")); result.setEqual(false); Method writeMethod = field.getWriteMethod(); String json = JSONObject.toJSONString(result); String methodName = writeMethod.getName(); Method resultWriteMethod = BeanUtils.findDeclaredMethodWithMinimalParameters(compareResult.getClass(), methodName); resultWriteMethod.invoke(compareResult, json); continue; } result.setFieldCode(field.getName()); result.setFieldName(EnumExcelField.getFieldValueNameByFieldValue(field.getName() != null ? field.getName() : "")); result.setEqual(!isSame); Method writeMethod = field.getWriteMethod(); String json = JSONObject.toJSONString(result); String methodName = writeMethod.getName(); Method resultWriteMethod = BeanUtils.findDeclaredMethodWithMinimalParameters(compareResult.getClass(), methodName); resultWriteMethod.invoke(compareResult, json); } } catch (IllegalAccessException | InvocationTargetException e) { throw new ServiceException(e); } if (diffCount > 0) { return compareResult; } return null; }
因为时间类型和Class对比完之后给实体类字段类型映射不上所以过滤一下
private static boolean isIgnore(PropertyDescriptor field) { String[] ignoreField = {"uploadTime", "uploadId", "class", "createDate","thirdOperation","secondOperation"}; return Arrays.asList(ignoreField).contains(field.getName()); }