Java对象转换工具类

Java 对象转换工具类

package com.xxx.xxxxxx.xxxx;
/**
 * @ClassName BeanUtil
 * @Description: bean util 处理工具类
 * @Author sxs
 * @Date 2020/7/15 18:19
 */

public class BeanUtil<T> {

    private static Logger logger = LoggerFactory.getLogger(BeanUtil.class);


    /**
     * Map -> Object
     *
     * @param des
     * @param params
     * @param <T>
     * @return
     */
    public static <T> T convertMapToObj(T des, Map<String, Object> params) {

        if (null == des || MapUtils.isEmpty(params)) {
            throw new BusinessException(ErrorCode.SERVER_ERROR, "param is null");
        }

        try {
            Optional.ofNullable(params).ifPresent(ps -> {

                ps.forEach((k, v) -> {

                    if (exist(k, des)) {

                        try {
                            Field field = des.getClass().getDeclaredField(k);
                            field.setAccessible(true);
                            field.set(des, v);
                        } catch (Exception e) {
                            logger.error("field set fail :{}", e);
                            throw new BusinessException(ErrorCode.SERVER_ERROR, ErrorCode.SERVER_ERROR.getMessage());
                        }
                    }
                });
            });
        } catch (Exception e) {
            logger.error("convertMapToObj fail :{}", e);
            throw new BusinessException(ErrorCode.SERVER_ERROR, "convertMapToObj fail");
        }

        return des;
    }


    /**
     * Object -> Object
     *
     * @param des
     * @param ori
     * @param <T>
     * @return
     */
    public static <T> T convertObjToObj(T des, T ori) {

        if (null == des || null == ori) {
            throw new BusinessException(ErrorCode.SERVER_ERROR, "param is null");
        }

        Optional.ofNullable(ori.getClass().getDeclaredFields()).ifPresent(fields -> {
            try {

                for (Field f : fields) {
                    f.setAccessible(true);

                    String fieldName = f.getName();
                    if (!fieldName.equals("serialVersionUID")) {
                        Optional<Object> value = Optional.ofNullable(f.get(ori));
                        if (value.isPresent()) {
                            if (exist(fieldName, des)){
                                Field field = des.getClass().getDeclaredField(fieldName);
                                field.setAccessible(true);
                                field.set(des, value.get());
                            }

                        }
                    }
                }
            } catch (Exception e) {
                logger.error("convertObjToObj fail :{}", e);
                throw new BusinessException(ErrorCode.SERVER_ERROR, "convertObjToObj fail");
            }

        });

        return des;
    }


    /**
     * Object -> Map
     *
     * @param des
     * @param ori
     * @param <T>
     * @return
     */
    public static <T> Map<String, Object> convertObjToMap(Map<String, Object> des, T ori) {

        if (MapUtils.isEmpty(des) || null == ori) {
            throw new BusinessException(ErrorCode.SERVER_ERROR, "param is null");
        }

        Optional.ofNullable(ori.getClass().getDeclaredFields()).ifPresent(fields -> {
            try {

                for (Field f : fields) {
                    f.setAccessible(true);
                    String fieldName = f.getName();
                    if (!fieldName.equals("serialVersionUID")) {
                        Optional<Object> value = Optional.ofNullable(f.get(ori));
                        if (value.isPresent()) {
                            des.put(fieldName, value.get());
                        }
                    }
                }
            } catch (Exception e) {
                logger.error("convertObjToMap fail :{}", e);
                throw new BusinessException(ErrorCode.SERVER_ERROR, "convertObjToMap fail");
            }

        });

        return des;
    }


    /**
     * R ori -> T des
     *
     * @param des
     * @param ori
     * @param <T>
     * @param <R>
     * @return
     */
    public static <T, R> T convertObjectToObject(T des, R ori) {

        if (null == des || null == ori) {
            throw new BusinessException(ErrorCode.SERVER_ERROR, "param is null");
        }

        Optional.ofNullable(ori.getClass().getDeclaredFields()).ifPresent(fields -> {
            try {

                for (Field f : fields) {
                    f.setAccessible(true);
                    String fieldName = f.getName();
                    if (!fieldName.equals("serialVersionUID")) {
                        Optional<Object> value = Optional.ofNullable(f.get(ori));
                        if (value.isPresent()) {
                            if (exist(fieldName, des)) {
                                Field field = des.getClass().getDeclaredField(fieldName);
                                field.setAccessible(true);
                                field.set(des, value.get());
                            }
                        }
                    }
                }
            } catch (Exception e) {
                logger.error("convertParamToObject fail :{}", e);
                throw new BusinessException(ErrorCode.SERVER_ERROR, "convertParamToObject fail");
            }

        });

        return des;
    }


    /**
     * check fieldName exist
     *
     * @param fieldName
     * @param obj
     * @return
     * @throws NoSuchFieldException
     */
    public static Boolean exist(String fieldName, Object obj) {

        if (obj == null || StringUtils.isEmpty(fieldName)) {
            return null;
        }

        AtomicBoolean flag = new AtomicBoolean(false);
        Optional.ofNullable(obj.getClass().getDeclaredFields()).ifPresent(
                fields -> {
                    for (Field f : fields) {
                        f.setAccessible(true);
                        if (f.getName().equals(fieldName)) {
                            flag.set(true);
                            break;
                        }
                    }
                }
        );

        return flag.get();
    }

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值