学无先后,达者为师

网站首页 编程语言 正文

BeanUtils工具类

作者:她丶如月中来 更新时间: 2022-07-18 编程语言

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,单个转换。

原文链接:https://blog.csdn.net/qq_43600166/article/details/125055077

栏目分类
最近更新