1:创建自定义注解
package com.test.crm.model;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 自定义注解
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD})//此注解作用于类和字段上
public @interface FieldTypeAnnotation {
String[] description();//没有指定defalut的,需要在注解的时候显式指明
}
2:属性添加注解(类也可以添加相同注解,视情况而定)
/**
* crm_highseas_install.no_followup_days (未跟进天数)
*
*/
@FieldTypeAnnotation(description = "未跟进天数")
private BigDecimal noFollowupDays;
/**
* crm_highseas_install.early_remind_days (提前提醒天数)
* @ibatorgenerated 2018-04-20 09:31:04
*/
@FieldTypeAnnotation(description = "提前提醒天数")
private BigDecimal earlyRemindDays;
3:方法调用
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import com.test.crm.model.FieldTypeAnnotation;
contrastObj(highseasInstall, install);//contrastObj(新数据的对象, 旧数据对象);
private static void contrastObj(Object newObj, Object oldObj) {
List<String> textList = Lists.newArrayList();
if (newObj instanceof CrmHighseasInstall && oldObj instanceof CrmHighseasInstall) {
try {
CrmHighseasInstall newPojo = (CrmHighseasInstall) newObj;
CrmHighseasInstall oldPojo = (CrmHighseasInstall) oldObj;
Class<? extends CrmHighseasInstall> clazz = newPojo.getClass();
Field[] fields = newPojo.getClass().getDeclaredFields();
for (Field field : fields) {
//判断属性上是否有此注解
boolean fieldHasAnno = field.isAnnotationPresent(FieldTypeAnnotation.class);
// //判断类上是否有此注解
// boolean fieldHasAnno = clazz.isAnnotationPresent(FieldTypeAnnotation.class);
if(fieldHasAnno){
PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
Method getMethod = pd.getReadMethod();
//自定义实现的注解类
FieldTypeAnnotation meta = field.getAnnotation(FieldTypeAnnotation.class);
Object o1 = getMethod.invoke(newPojo);
Object o2 = getMethod.invoke(oldPojo);
String s1 = o1 == null ? "" : o1.toString();//避免空指针异常
String s2 = o2 == null ? "" : o2.toString();//避免空指针异常
if (!s1.equals(s2)) {
textList.add("不一样的属性:" +Arrays.asList(meta.description()).toString() + "属性值:[" + s1 + "," + s2 + "]");
System.out.println(meta.description());
System.out.println(textList);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
for (Object object : textList) {
System.out.println(object);
}
}
}
结果:[不一样的属性:[未跟进天数]属性值:[11,111], 不一样的属性:[提前提醒天数]属性值:[22,222]]
参考网站:https://blog.csdn.net/raynaing/article/details/53442984