通过注解的方式实现对象指定属性前后对比记录

指定属性对比注解

@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface OperationLog {
String name() default "";
}

对比工具类
@Slf4j
public class OperationLogUtil {

public static String operationLog(Object newObject, Object oldObject) {
Class<?> clazz = newObject.getClass();
log.info("操作日志--->需要记录的类:" + clazz.getName());

List<Field> fields = new ArrayList<>();
Class<?> tempClass = clazz;
while (tempClass != null && !Objects.equals("Object", tempClass.getName())){
fields.addAll(Arrays.asList(tempClass.getDeclaredFields()));
tempClass = tempClass.getSuperclass();
}

log.info("操作日志--->需要记录的属性:" + fields.toString());

StringBuilder str = new StringBuilder();
Set<String> uniqueField = new HashSet<>();

fields.forEach(field -> {
if(field.isAnnotationPresent(OperationLog.class)){

if(!uniqueField.add(field.getName())){
return;
}

OperationLog operationLogChinese = field.getAnnotation(OperationLog.class);
String name = operationLogChinese.name();

try {
PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
Method getMethod = pd.getReadMethod();

Object newValue = getMethod.invoke(newObject);
Object oldValue = getMethod.invoke(oldObject);

if (null == oldValue || StringUtils.isBlank(oldValue.toString())){
oldValue = "无";
}

if (null == newValue || StringUtils.isBlank(newValue.toString())){
newValue = "无";
}

if(!Objects.equals(newValue.toString(), oldValue.toString())){
str.append(name).append(":由[").append(oldValue).append("]改成[").append(newValue).append("];");
}
} catch (Exception e) {
e.printStackTrace();
}
}
});

log.info("日志结果:" + str.toString());

return str.toString();
}
上一篇:数据更新DOM未更新的问题解决一(vue 深度响应初步了解)


下一篇:C#利用微软自带库进行中文繁体和简体之间的转换的代码