首先Maven引入Hutool依赖:
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.21</version> <!-- 请根据实际最新版本调整 -->
</dependency>
测试:
1、创建一个User实体类
@Data
@RequiredArgsConstructor
@AllArgsConstructor
public class User {
private Long id;
private String name;
private String sex;
private String address;
}
2、代码测试:
public void auditChanges() {
User oldEntity = new User(1L,"小明", "男", "广州");
User newEntity = new User(1L,"小明", "女", "深圳");
// 获取对象的属性
Map<String, Object> oldMap = BeanUtil.beanToMap(oldEntity);
Map<String, Object> newMap = BeanUtil.beanToMap(newEntity);
System.out.println("-----对象User字段的变化记录------");
oldMap.forEach((key, oldValue) -> {
Object newValue = newMap.get(key);
if (newValue != null && !oldValue.equals(newValue)) {
System.out.println("字段名称: " + key + ", 旧值: " + oldValue + ", 新值: " + newValue);
}
});
}
3、运行结果: