两个相同类型的对象比较不同内容
/**
* 比较两个类型一样的对象中的值变更
* @param pre 变化前的对象
* @param last 变化后的对象
* @param map 需要比较的属性 map.put(“id”,“主键”);
* @return
*/
public static String compare(Object pre, Object last, Map<String,Object> map){
StringBuilder result=new StringBuilder();
Class preClass = pre.getClass();
Class lastClass = last.getClass();
//判断两个
if(!preClass.equals(lastClass)){
throw new RuntimeException(“两个对象类型不一致”);
}
if(CollectionUtils.isEmpty(map)){
throw new RuntimeException(“需要比较的属性不能为空”);
}
Set keys = map.keySet();
for(String key : keys){
//获取方法名
String methodName = “get” + key.substring(0, 1).toUpperCase() + key.substring(1);
Method preMethod;
Method lastMethod;
Object preValue;
Object lastValue;
try {
preMethod= preClass.getMethod(methodName);
lastMethod = lastClass.getMethod(methodName);
preValue = preMethod.invoke(pre);
lastValue = lastMethod.invoke(last);
}catch (Exception e){
throw new RuntimeException(“获取不到该方法”,e);
}
if("".equals(preValue)){
preValue =null;
}
if("".equals(lastValue)){
lastValue =null;
}
//如果前后两个值都是空,那么无需比较
if(!ObjectUtils.allNotNull(preValue)&&!ObjectUtils.allNotNull(lastValue)){
continue;
}else if(!ObjectUtils.allNotNull(preValue)&&ObjectUtils.allNotNull(lastValue)){
//前值为空,后值不为空
result.append(map.get(key) +“由空变为”+lastValue+";");
}else if(ObjectUtils.allNotNull(preValue)&&!ObjectUtils.allNotNull(lastValue)){
//前值不为空,后值为空
result.append(map.get(key)+“由”+preValue+“变为空;”);
}else if(ObjectUtils.allNotNull(preValue)&&ObjectUtils.allNotNull(lastValue)){
//两个都不为空
if (preValue.equals(lastValue)){
continue;
}
result.append(map.get(key)+“由”+preValue+“变为”+lastValue+";");
}
}
return result.toString();
}