反射的使用

利用反射調用實體對象的get方法,get方法的方法名根據實體類的屬性名生成

/**
* 封裝json數據
* @param resumes
* @return
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public String generate(List<Resume> resumes) {

    // 實體類的字段名和json串中的字段名的映射關係存儲在數據表中,將字段映射表中的數據放入map中
    Map<String, String> mstColumnReferenceMap = new HashMap<>();
    List<MstColumnReference> mstColumnReferenceList = mstColumnReferenceRepository.findAllByOrderByIdAsc();
    for (MstColumnReference mstColumnReference : mstColumnReferenceList) {
        mstColumnReferenceMap.put(mstColumnReference.getTableColumn(), mstColumnReference.getJobColumn());
    }

    List<Map<String, Object>> resumeJsonList = new ArrayList<>();
    for(Resume resume : resumes) {
        Map<String, Object> map = new HashMap<>();
        for(Map.Entry<String,String> entity : mstColumnReferenceMap.entrySet()) {
            String fieldName = entity.getKey();

            // 根據屬性名生成get方法的方法名
            String getMethodName = "get"
                + fieldName.substring(0, 1).toUpperCase()
                + fieldName.substring(1);

            String[] str = getMethodName.split("_");
            // 去掉中間的下劃線
            if (str.length > 1) {
                StringBuilder sb = new StringBuilder();
                sb.append(str[0]);
                for (int i = 1; i < str.length; ++i) {
                    sb.append(str[i].substring(0, 1).toUpperCase() + str[i].substring(1));
                }
                getMethodName = sb.toString();
            }

            try {
                Class tCls = resume.getClass();
                Method getMethod = tCls.getMethod(getMethodName, new Class[]{});
                Object value = getMethod.invoke(resume, new Object[]{});
                String textValue = null;

                if(value != null) {
                    if (value instanceof Date) {
                        // 處理日期格式的屬性
                        Date date = (Date) value;
                        textValue = DateUtil.formartDate(date);
                    } else {
                        //其它數據類型都當作字符串簡單處理
                        textValue = value.toString();
                    }
                } else {
                    textValue = "";
                }
                map.put(entity.getValue(), textValue);
            } catch (Exception e) {

                log.warn("【字段映射錯誤, 字段名:{}->{}】", entity.getKey(), entity.getValue());
                log.warn("錯誤信息:{}", e.getMessage());
            }
        }

        resumeJsonList.add(map);
    }

    return EsbServiceUtil.objectToJson(resumeJsonList);
}

參考文章:https://blog.csdn.net/panpan96/article/details/76566475

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