反射的使用

利用反射调用实体对象的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.youkuaiyun.com/panpan96/article/details/76566475

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值