/**
*
* @Description: 示例
* @Authoradmin: zuo
* @Date 2020/5/30 9:01 AM
* Version 1.0.0
*/
@Slf4j
public class AaaDemo {
public static void main(String[] args) {
Dog oldDog = new Dog();
oldDog.setAge(1);
oldDog.setName("呆瓜");
Dog newDog = new Dog();
newDog.setAge(2);
newDog.setName("西瓜");
String diff = contrastObj(oldDog, newDog, Dog.class);
System.out.println(diff);
// 姓名:旧值:呆瓜,新值:西瓜
// age:旧值:1,新值:2
}
/**
* 对比两个bean的差异属性
*
* @param oldBean
* @param newBean
* @param clazz
* @param <T>
* @return
*/
public static <T> String contrastObj(Object oldBean, Object newBean, Class<T> clazz) {
String str = "";
T pojo1 = (T) oldBean;
T pojo2 = (T) newBean;
try {
Field[] fields = clazz.getDeclaredFields();
int i = 1;
for (Field field : fields) {
if ("id".equals(field.getName())) {
continue;
}
PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
Method getMethod = pd.getReadMethod();
Object o1 = getMethod.invoke(pojo1);
Object o2 = getMethod.invoke(pojo2);
//如果新值为空,不修改旧值
if (o2 == null) {
continue;
}
if (!o2.equals(o1)) {
if (i != 1) {
str += "\r\n";
}
// 要显示的字段名
FieldDesc declaredAnnotation = field.getDeclaredAnnotation(FieldDesc.class);
String customFieldValue = declaredAnnotation != null && StringUtils.isNotEmpty(declaredAnnotation.value()) ? declaredAnnotation.value() : field.getName();
str += customFieldValue + ":旧值:" + o1 + ",新值:" + o2;
i++;
}
}
} catch (Exception e) {
log.error("字段对比失败:{}", e);
}
return str;
}
}
/**
*
* @Description: 实体类:狗
* @Authoradmin: zuo
* @Date 2020/5/30 9:07 AM
* Version 1.0.0
*/
public class Dog {
@FieldDesc(value = "姓名")
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
/**
*
* @Description: 字段描述注解类
* @Authoradmin: zuo
* @Date 2020/5/30 9:13 AM
* Version 1.0.0
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface FieldDesc {
String value();
}