1.写个注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Compare {
String value();
}
2.工具类
public class ObjectComparator {
public static List<Map<String, String>> compare(Object oldObj, Object newObj) {
List<Map<String,String>> resultList= new ArrayList<>();
try {
// 获取所有字段
Field[] fields = oldObj.getClass().getDeclaredFields();
// 遍历所有字段
for (Field field : fields) {
// 如果字段被 @Compare 注解标注
if (field.isAnnotationPresent(Compare.class)) {
// 获取字段的中文名
String fieldName = field.getAnnotation(Compare.class).value();
// 设置字段可访问
field.setAccessible(true);
// 获取字段的旧值和新值
Object oldValue = field.get(oldObj);
Object newValue = field.get(newObj);
// 如果值不相等
if (!Objects.equals(oldValue, newValue)) {
Map<String, String> result = new HashMap<>(16);
// 将字段名和值添加到结果中
result.put(fieldName, "旧值:" + oldValue + ",新值:" + newValue);
resultList.add(result);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return resultList;
}
3.实体类
@Data
public class UserInfo {
@Compare("姓名")
private String name;
@Compare("性别")
private String sex;
}
4.测试
public class Test {
public static void main(String[] args) {
UserInfo oldUser = new UserInfo();
oldUser.setName("张三");
oldUser.setSex("男");
UserInfo newUser = new UserInfo();
newUser.setName("李四");
newUser.setSex("女");
List<Map<String, String>> changes = ObjectComparator.compare(oldUser, newUser);
for(int i=0;i<changes.size();i++){
Map<String,String> map = changes.get(i);
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}
}
}
5.结果

该文展示了如何使用Java注解和反射机制创建一个工具类,用于比较两个对象实例的特定字段值。在实体类中,定义了一个名为@Compare的注解来标记需要比较的字段。在ObjectComparator工具类中,遍历对象的字段,查找带有@Compare注解的字段并比较它们的新旧值,当值不相等时,记录差异。测试用例演示了如何使用这个工具类来找出两个UserInfo对象之间的变化。

5111

被折叠的 条评论
为什么被折叠?



