由於要比較每個對象的屬性的值是否改變,若是每一個對象都寫一遍比較的方法,不只繁瑣,複用性也很差。因此咱們用反射的機制,
得到每一個對象的字段,獲得字段的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
獲得修改的內容後,紀錄到歷史表中。 對象