1、java的反射机制,通过注解实现。
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* 自定义注解
* @author Administrator
*
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface LogCompar {
String value();
}
2、在实体类上添加自定义注解@实体类名称,如:@LogCompar
3、工具类
import java.lang.reflect.Field;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.aohaichina.sys.domain.User;
/**
* 对比工具类
* @author Administrator
*
*/
public class CompareUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(CompareUtil.class);
/**
* @param oldObj 原数据对象
* @param newObj 修改后数据对象
*/
public String addRecord(Object oldObj, Object newObj){
String str = "";
try {
// 得到类对象
Class<? extends Object> class1 = oldObj.getClass();
Class<? extends Object> class2 = newObj.getClass();
if(!class1.equals(class2)){
throw new RuntimeException("请传入两个相同的实体类对象");
}
// 得到属性集合
Field[] fields1 = class1.getDeclaredFields();
Field[] fields2 = class2.getDeclaredFields();
StringBuffer info = new StringBuffer();
Long id = null;
int i=1;
for (Field field1 : fields1) {
field1.setAccessible(true); // 设置属性是可以访问的(私有的也可以)
if(id == null && field1.getName().equals("id")){
id = (Long)field1.get(oldObj);
}
for (Field field2 : fields2) {
field2.setAccessible(true); // 设置属性是可以访问的(私有的也可以)
if(field1.equals(field2)){ // 比较属性名是否一样
if(field2.get(newObj) == null || StringUtils.isEmpty(field2.get(newObj) + "")){
break; // 属性名称一样就退出二级循环
}
if(!field1.get(oldObj).equals(field2.get(newObj))){ // 比较属性值是否一样
// 得到注解
LogCompar pn = field1.getAnnotation(LogCompar.class);
if(pn != null){
if(i!=1){
str+=",";
}
str +=""+pn.value() + ":\"" + field1.get(oldObj) + "\" 改成 \"" + field2.get(newObj) + "\""+"";
i++;
}
}
break; // 属性名称一样就退出二级循环
}
}
}
if(info.length() != 0){
// 设置日志信息
System.out.println(info.length() == 0 ? info.toString() : info.substring(0, info.length() - 1));
}
} catch (RuntimeException e) {
e.printStackTrace();
LOGGER.error(e.getMessage());
} catch (Exception e) {
e.printStackTrace();
LOGGER.error("属性内容更改前后验证错误,日志无法被记录!");
}
return str;
}
/**
* 测试
* @param args
*/
public static void main(String[] args) {
User u1 = new User();
u1.setLoginname("T-1711");
u1.setName("pbm");
User u2 = new User();
u2.setLoginname("T-1722");
u2.setName("pbm2");
CompareUtil compareUtil = new CompareUtil();
String resultIn = compareUtil.addRecord(u1,u2);
System.out.println(resultIn);
}
}
4、运行结果