@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface OperateLog {
String name() default "";
/**
* 根据自动转换 数值 对应名称
*/
boolean isBooleanValue() default false;
}
public class OperateLogUtil {
private static Set<String> unCompareFiledSet = Sets.newHashSet("serialVersionUID",
"createTime",
"modifyTime");
/**
* 对象比较器
*/
public static <T> String compareObject(Object oldBean, Object newBean) {
StringBuilder str = new StringBuilder();
T pojo1 = (T) oldBean;
T pojo2 = (T) newBean;
try {
Class clazz = pojo1.getClass();
Field[] fields = pojo1.getClass().getDeclaredFields();
int i = 1;
for (Field field : fields) {
if (unCompareFiledSet.contains(field.getName())) {
continue;
}
String name;
boolean booleanValue = false;
if (field.isAnnotationPresent(OperateLog.class)) {
OperateLog dt = field.getAnnotation(OperateLog.class);
booleanValue = dt.isBooleanValue();
name = dt.name();
} else {
continue;
}
PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
Method getMethod = pd.getReadMethod();
Object o1 = getMethod.invoke(pojo1);
Object o2 = getMethod.invoke(pojo2);
if (o1 == null && o2 == null) {
continue;
}
if (!Objects.equals(o1, o2)) {
if (i != 1) {
str.append(";");
}
if (o1 == null) {
o1 = "空";
}
if (o2 == null) {
o2 = "空";
}
if (booleanValue) {
if (o1 instanceof Boolean) {
o1 = o1.equals(true) ? "是" : "否";
}
if (o2 instanceof Boolean) {
o2 = o2.equals(true) ? "是" : "否";
}
if (o1 instanceof Integer) {
o1 = o1.equals(1) ? "是" : "否";
}
if (o2 instanceof Integer) {
o2 = o2.equals(1) ? "是" : "否";
}
}
if (o1 instanceof Date) {
o1 = TimeUtil.formatDate((Date) o1);
}
if (o2 instanceof Date) {
o2 = TimeUtil.formatDate((Date) o2);
}
str.append("修改").append(name).append(":前:[").append(o1).append("],后:[").append(o2).append("]");
i++;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return str.toString();
}
}
Contract contract = new Contract();
contract.setAutoRenewYear(0);
contract.setContactAddress("飞机");
contract.setNo("1212");
contract.setDeposit(BigDecimal.ONE);
contract.setEndTime(new Date());
contract.setHasDeposit(true);
Contract contract1 = new Contract();
contract1.setAutoRenewYear(1);
contract1.setContactAddress("飞机121");
contract1.setDeposit(BigDecimal.TEN);
contract1.setHasDeposit(false);
String s = compareObject(contract, contract1);
System.out.println(s);
测试结果:
修改合同号:前:[1212],后:[空];修改终止时间:前:[2022-06-23],后:[空];修改是否自动续签:前:[否],后:[是];修改保证金:前:[1],后:[10];修改保证金是否缴纳:前:[是],后:[否];修改邮寄地址:前:[飞机],后:[飞机121]