/**
* 比较同一个类的两个对象示例的不一样的内容,并输出不一样的字段内容
* <br/> 属性字段为基本数据类型
*
* @author FALSE KING create
* @date 2016年9月23日 下午4:36:38
*/
public class ModelComparator<T> {
/**
* 比较内容,输出不一样的字段内容<br/>
* 属性字段为基本数据类型
*
* @param oldModel 修改前的对象
* @param newModel 修改后的对象
* @param exceptFileds 排除的属性字段列表
* @return
*/
public String compare(T oldModel,T newModel,List<String> exceptFileds) {
List<String> result = new ArrayList();
Field[] oldFields = oldModel.getClass().getDeclaredFields();
for (Field f : oldFields) {
String name = f.getName();
if(CollectionUtils.isNotEmpty(exceptFileds) && exceptFileds.contains(name)){
continue;
}
String methodName = "get" + name.substring(0, 1).toUpperCase() +
name.substring(1);
try {
Object oldVal = oldModel.getClass().getMethod(methodName).invoke(oldModel);
Object newVal = newModel.getClass().getMethod(methodName).invoke(newModel);
if(oldVal != null && !oldVal.equals(newVal)){
result.add(String.valueOf(oldVal) + "修改为" +String.valueOf(newVal)+ "\n") ;
}
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e) {
}
}
String str = "";
if(CollectionUtils.isNotEmpty(result)){
str = result.stream().reduce((sum,e)->sum += e).get();
}
return str;
}
}