BeanUtils工具类

BeanUtils工具类转换

在日常开发中经常会遇到对象转换,最常用的对象转换工具就是BeanUtils,也就是使用BeanUtils.copyProperties(Object source, Object target)方法进行转换。为了使用更方便,因为对BeanUtils进行一个简单的封装,实现BeanUtils对泛型的转换。这里封装了一个叫ConvertUtils的类,代码如下:

/**
 * @Author: Greyfus
 * @Create: 2022-05-11 10:25
 * @Version:
 * @Description:
 */
package vgc.itp.rtm.sop.pojo.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class ConvertUtils {

    private static Logger LOG = LoggerFactory.getLogger(ConvertUtils.class);

    private ConvertUtils() {

    }

    public static <S, T> T convert(S sourceObject, Class<T> targetClass) {
        if (Objects.isNull(sourceObject)) {
            return null;
        }
        T targetObject = null;
        try {
            targetObject = targetClass.newInstance();
        } catch (Exception e) {
            LOG.error("object convert error : {}", e.getMessage());
        }
        BeanUtils.copyProperties(sourceObject, targetObject);
        return targetObject;
    }

    public static <S, T> ArrayList<T> convertList(List<S> sourceList,Class<T> targetClass) {
        if (CollectionUtils.isEmpty(sourceList)) {
            return null;
        }
        ArrayList<T> targetList = new ArrayList<>();
        for (int index = 0; index < sourceList.size(); index++) {
            T targetObject = null;
            try {
                targetObject = targetClass.newInstance();
            } catch (Exception e) {
                LOG.error("object convert error : {}", e.getMessage());
            }
            BeanUtils.copyProperties(sourceList.get(index),targetObject);
            targetList.add(targetObject);
        }
        return targetList;
    }
}

ConvertUtils类实现对单个对象和List的转换。使用也非常简单,比如有一个Model对象需要转换为VehicleModel对象,那么只需要

ConvertUtils.convertList(model, VehicleModel.class);//即可实现model对象转换为VehicleModel

对于List的转换也是如此,只需要调用ConvertUtils.convertList()方法即可,比如将一个l类型为List的 vehileList转为List类型的对象,只需要

ConvertUtils.convertList(vehileList, SopVhicle.class);

之前一直在找直接将整个List对象转换的方法,但是BeanUtils.copyProperties并支持整个List对象的转换,所以只能遍历List,单个转换。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值