Java反射—記錄對象前後修改的內容使用註解(下)

一、關於反射
上一篇已講 這篇就不多贅述直接上代碼

這次比上次有所不同的地方在於 之前是硬編碼 這次使用了註解來獲取屬性對應中文

註解類

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface PropertyMsg {


    String enumStr() default "";
    String value() default "";

}

實體

/**
 * @author wyy
 * @version 1.0
 * @date 2019/7/17 18:05
 * @description
 **/
@Validated
@Data
public class ModelBO {
    /**
     * 主鍵id
     */
    private String id;


    /**
     * 姓名
     */
    @PropertyMsg(value = "姓名")
    @NotBlank(message = "姓名不能爲空")
    private String name;

    /**
     * 性別
     */
    @PropertyMsg(value = "性別",enumStr = "0,女|1,男")
    @NotNull(message = "性別不能爲空")
    private Integer sex;


    /**
     * 年齡
     */
    @PropertyMsg(value = "年齡")
    @NotNull(message = "年齡不能爲空!")
    private Integer age;

public ModelBO(String  name,Integer  sex,Integer age){
		this.name =name;
		this.sex =sex;
		this.age = age;
}
}

傳入兩個對象   分別是
oldBean:數據庫查出來 或者老舊的數據實體
newBean:前端傳到後端 或者
/**
 * @author wyy
 * @version 1.0
 * @date 2019/8/28 16:32
 * @description 實體屬性比較工具
 * 比較兩個實體屬性值是否相等(判斷更新前/後數據是否發生改動)
 * 不相等則把兩個數據分別存儲到兩個map裏
 **/
public class JudgeAttributesIsEqualedUtil<T> {
  public static <T> String contrastObj(Object oldBean, Object newBean) {
        // 創建字符串拼接對象
        StringBuilder str = new StringBuilder();
        // 轉換爲傳入的泛型T
        T pojo1 = (T) oldBean;
        T pojo2 = (T) newBean;
        // 通過反射獲取類的Class對象
        Class clazz = pojo1.getClass();
        Class clazz1 = pojo2.getClass();
        // 獲取類型及字段屬性
        Field[] fields = clazz1.getDeclaredFields();
        return ToGetAttributeNameUtil.toGetAttributeName(fields, pojo1, pojo2, str,clazz,clazz1);
    }
    }
/**
 * @author wyy
 * @version 1.0
 * @date 2019/8/28 18:15
 * @description
 **/
public class ToGetAttributeNameUtil {
 public static<T>  String toGetAttributeName(Field[] fields, T pojo1, T pojo2, StringBuilder str, Class clazz, Class clazz1){
        for(Field x : fields){
            //如果兩個對象沒有一個進行註解標註
            if(x.isAnnotationPresent(PropertyMsg.class)) {
                try {
                    PropertyDescriptor pd = new PropertyDescriptor(x.getName(), clazz);
                    PropertyDescriptor pd1 = new PropertyDescriptor(x.getName(), clazz1);
                    // 獲取對應屬性值
                    Method getMethod = pd.getReadMethod();
                    Object o1 = getMethod.invoke(pojo1);
                    Method getMethod1 = pd1.getReadMethod();
                    Object o2 = getMethod1.invoke(pojo2);
                    if (o1 == null && o2 == null) {
                        continue;
                    }
                    if (o1 == null){
                        o1="";
                    }
                    if (o2 == null){
                        o2="";
                    }
                    if (!o1.toString().equals(o2.toString())) {
                        if (StringUtils.isNotBlank(x.getAnnotation(PropertyMsg.class).enumStr())) {
                            Map<String, String> stringStringMap = Arrays.stream(x.getAnnotation(PropertyMsg.class).enumStr().split("\\|"))
                                    .map(s -> {
                                        //如果註解開頭枚舉爲空則賦值"" 應對疊單標記等問題
                                        String[] split = s.split(",");
                                        if(split.length == 1){
                                            String[] s1 = new String[2];
                                            s1[0] = "";
                                            s1[1] = split[0];
                                            return s1;
                                        }
                                        return split;
                                    })
                                    .collect(Collectors.toMap(b -> b[0].trim(), b -> b[1].trim()));
                            o1 = stringStringMap.get(o1.toString());
                            o2 = stringStringMap.get(o2.toString());
                        }
                        str.append( x.getAnnotation(PropertyMsg.class).value() + ":" + " 由 \"" + o1 + "\"改爲\"" + o2 + "\";");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return str.toString();
  }
}

測試

public class TestChange {

    public static void main(String[] args) {
        ModelBO u1 = new ModelBO ("劉德華", 1, 40);
        ModelBO u2 = new ModelBO ("郭富城", 1, 43);
        JudgeAttributesIsEqualedUtil<ModelBO > t = new JudgeAttributesIsEqualedUtil<>();
        String str = t.contrastObj(u1, u2);
        if (str.equals("")) {
            System.out.println("未有改變");
        } else {
            System.out.println(str);
        }
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章