BeanUtils工具类使用示例说明

戚薇 Java经验 发布时间:2023-06-14 17:17:07 阅读数:9913 1
下文笔者讲述BeanUtils工具类简介说明,如下所示

BeanUtils工具类简介

BeanUtils常用于对象复制,对象转换
   如:BeanUtils.copyProperties(Object source, Object target)


如:我们可借助BeanUtils.copyProperties 实现类的转换
例:工具类的编写
package com.java265.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.convertList(model, Test.class);//即可实现model对象转换为Test

//List转换
ConvertUtils.convertList(modelList,Test.class);
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202306/16867342536789.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者