由于要比较每个对象的属性的值是否改变,若是每一个对象都写一遍比较的方法,不只繁琐,复用性也很差。因此咱们用反射的机制,
得到每一个对象的字段,获得字段的get方法,得到每一个字段的新旧值,做比较,记录修改的历史记录。
public class GetModifyHistoryUtil {
public static String getEditHistory(Object oldObj,Object newObj){
String content = "";
//得到属性
Field[] fields = oldObj.getClass().getDeclaredFields();
for (Field field : fields) {
try {
PropertyDescriptor descriptor = new PropertyDescriptor(field.getName(), oldObj.getClass());
Method getMethod = descriptor.getReadMethod();//得到get方法
Object oldVal = getMethod.invoke(oldObj);
Object newVal = getMethod.invoke(newObj);
if(oldVal != null || newVal != null){
if(oldVal == null && newVal != null){
if(StringUtils.isNotBlank(newVal.toString()))
content += "增长"+field.getName()+"字段的值为"+newVal.toString()+"; ";
}else if(oldVal != null && newVal == null)
content += "删除了"+field.getName()+"字段的内容["+ oldVal.toString() +"]; ";
else if(oldVal != null && newVal != null){
if(!oldVal.toString().equals(newVal.toString()))
content += "修改"+field.getName()+"字段内容["+oldVal.toString()+"]为:"+newVal.toString() + "; ";
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return content;
}
} spa
获得修改的内容后,纪录到历史表中。 对象