前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Converter集合转换

Converter集合转换

作者头像
阿超
发布2022-08-21 13:41:10
2840
发布2022-08-21 13:41:10
举报
文章被收录于专栏:快乐阿超快乐阿超

前两天写了mapstruct的spring拓展

里面提到了一个Converter

一般我们是对象之间互转,如果是集合的话,可以用Stream#map去一个一个转换

实际上org.springframework.core.convert.ConversionService也为我们提供了参数为org.springframework.core.convert.TypeDescriptor的转换

例如我这里封装一个集合之间的转换

SpringContextHolder工具类

代码语言:javascript
复制
import java.util.ArrayList;
import java.util.List;

import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.util.CollectionUtils;

import lombok.experimental.UtilityClass;

/**
 * 转换工具类
 *
 * @author <achao1441470436@gmail.com>
 * @since 2022/5/7 18:56
 */
@UtilityClass
public class ConvertUtil {

    private static final ConversionService CONVERSION_SERVICE = SpringContextHolder.getBean(ConversionService.class);


    public static <T> T convert(@NonNull Object source, Class<T> targetType) {
        return CONVERSION_SERVICE.convert(source, targetType);
    }


    public static Object convert(@NonNull Object source, @Nullable TypeDescriptor sourceType, TypeDescriptor targetType) {
        return CONVERSION_SERVICE.convert(source, sourceType, targetType);
    }

    @SuppressWarnings("unchecked")
    public static <T, R> List<R> convertList(List<T> source, Class<R> targetClass) {
        if (CollectionUtils.isEmpty(source)) {
            return new ArrayList<>();
        }
        return (List<R>) convert(source, TypeDescriptor.collection(List.class,
                        TypeDescriptor.valueOf(source.get(0).getClass())),
                TypeDescriptor.collection(List.class, TypeDescriptor.valueOf(targetClass)));
    }
}

使用起来只需要:

代码语言:javascript
复制
final List<UserVO> result = ConvertUtil.convertList(userList, UserVO.class);

注意前置条件需要配置了UserUserVO的转换器

如何配置?本篇博客第一行有说明

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-05-12,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档