您的位置:首页 > 其它

添加用户操作历史记录时,纪录用户修改内容用反射技术实现

2013-09-29 00:00 477 查看
因为要比较每一个对象的属性的值是否改变,如果每个对象都写一遍比较的方法,不仅繁琐,复用性也不好。所以我们用反射的机制,

获得每个对象的字段,得到字段的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;

}

}

得到修改的内容后,纪录到历史表中。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐