吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 463|回复: 15
收起左侧

[Java 原创] BeanUtils.copyProperties封装拷贝List对象

[复制链接]
COXS 发表于 2024-3-14 10:45
BeanUtils.copyProperties();确实为我们做了很多事情,虽然不能完美完成深拷贝,但是对于po、vo、dto的拷贝已经足够用了。但是其还是有一些不够完美的地方

[Java] 纯文本查看 复制代码
package net.fkzg.system.common.util;
 
import net.fkzg.system.common.exception.SystemServiceException;
import org.springframework.beans.BeanUtils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
 
public class BeanCopyTool {
 
    public static <T> T convertCopyBean(Object source, Class<T> clazz) {
        if (source == null) {
            return null;
        }
        try {
            T target = clazz.newInstance();
            BeanUtils.copyProperties(source, target);
            return target;
        } catch (Exception ex) {
            throw new SystemServiceException(ex.getMessage());
        }
    }
 
    public static <T, E> List<T> convertCopyList(Collection<E> oldList, Class<T> clazz) {
        List<T> newList = new ArrayList<>();
        if (oldList != null && !oldList.isEmpty()) {
            try {
                for (Object item : oldList) {
                    T newObj = clazz.newInstance();
                    BeanUtils.copyProperties(item, newObj);
                    newList.add(newObj);
                }
            } catch (Exception ex) {
                throw new SystemServiceException(ex.getMessage());
            }
        }
        return newList;
    }
 
 
}

免费评分

参与人数 1吾爱币 +7 热心值 +1 收起 理由
爱飞的猫 + 7 + 1 欢迎分析讨论交流,吾爱破解论坛有你更精彩!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

mabin 发表于 2024-3-14 17:42
本帖最后由 mabin 于 2024-3-14 17:44 编辑

这个orika下的进行属性映射性能和使用复杂性也都还可以,推荐尝试

                        <dependency>
                <groupId>ma.glasnost.orika</groupId>
                <artifactId>orika-core</artifactId>
                <version>1.5.4</version>
            </dependency>
import ma.glasnost.orika.MapperFacade;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import ma.glasnost.orika.metadata.ClassMapBuilder;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description: Orika封装的工具类
 * @date 2021/7/2 16:16
 * @AuThor mb
 */

public class OrikaUtils {

    private static final MapperFactory FACTORY = new DefaultMapperFactory.Builder().build();
    /**
     * 缓存实例集合
     */
    private static Map<String, MapperFacade> cacheMapper = new ConcurrentHashMap<>();

    private MapperFacade mapper;

    public OrikaUtils(MapperFacade mapper) {
        this.mapper = mapper;
    }

    /**
     * 转换实体函数
     *
     * @Param sourceEntity 源实体
     * @param targetClass  目标类对象
     * @param refMap       配置源类与目标类不同字段名映射
     * @param <S>          源泛型
     * @param <T>          目标泛型
     * @Return 目标实体
     */
    public static <S, T> T convert(S sourceEntity, Class<T> targetClass, Map<String, String> refMap) {
        if (sourceEntity == null) {
            return null;
        }
        return classMap(sourceEntity.getClass(), targetClass, refMap).map(sourceEntity, targetClass);
    }

    /**
     * 转换实体函数
     *
     * @param sourceEntity 源实体
     * @param targetClass  目标类对象
     * @param <S>          源泛型
     * @param <T>          目标泛型
     * @return 目标实体
     */
    public static <S, T> T convert(S sourceEntity, Class<T> targetClass) {
        return convert(sourceEntity, targetClass, null);
    }

    /**
     * 转换实体集合函数
     *
     * @param sourceEntityList 源实体集合
     * @param targetClass      目标类对象
     * @param refMap           配置源类与目标类不同字段名映射
     * @param <S>              源泛型
     * @param <T>              目标泛型
     * @return 目标实体集合
     */
    public static <S, T> List<T> convertList(List<S> sourceEntityList, Class<T> targetClass, Map<String, String> refMap) {
        if (sourceEntityList == null) {
            return null;
        }
        if (sourceEntityList.size() == 0) {
            return new ArrayList<>(0);
        }
        return classMap(sourceEntityList.get(0).getClass(), targetClass, refMap).mapAsList(sourceEntityList, targetClass);
    }

    /**
     * 转换实体集合函数
     *
     * @param sourceEntityList 源实体集合
     * @param targetClass      目标类对象
     * @param <S>              源泛型
     * @param <T>              目标泛型
     * @return 目标实体集合
     */
    public static <S, T> List<T> convertList(List<S> sourceEntityList, Class<T> targetClass) {
        return convertList(sourceEntityList, targetClass, null);
    }

    /**
     * @param source
     * @param target
     * @param <V>
     * @param <P>
     * @return
     */
    public static <V, P> OrikaUtils classMap(Class<V> source, Class<P> target) {
        return classMap(source, target, null);
    }

    /**
     * 属性名称一致可用
     *
     * @param source
     * @param target
     * @param <V>
     * @param <P>
     * @return
     */
    public static synchronized <V, P> OrikaUtils classMap(Class<V> source, Class<P> target, Map<String, String> refMap) {
        String key = source.getCanonicalName() + ":" + target.getCanonicalName();
        if (cacheMapper.containsKey(key)) {
            return new OrikaUtils(cacheMapper.get(key));
        }
        if (CollectionUtils.isEmpty(refMap)) {
            FACTORY.classMap(source, target).byDefault().register();
        } else {
            ClassMapBuilder<V, P> classMapBuilder = FACTORY.classMap(source, target);
            refMap.forEach(classMapBuilder::field);
            classMapBuilder.byDefault().register();
        }
        MapperFacade mapperFacade = FACTORY.getMapperFacade();
        cacheMapper.put(key, mapperFacade);

        return new OrikaUtils(mapperFacade);
    }

    /**
     * 复制对象
     *
     * @param source
     * @param target
     * @param <V>
     * @param <P>
     * @return
     */
    public <V, P> P map(V source, Class<P> target) {
        return mapper.map(source, target);
    }

    /**
     * 复制List
     *
     * @param source
     * @param target
     * @param <V>
     * @param <P>
     * @return
     */
    public <V, P> List<P> mapAsList(List<V> source, Class<P> target) {
        return CollectionUtils.isEmpty(source) ? Collections.emptyList() : mapper.mapAsList(source, target);
    }

}

免费评分

参与人数 1吾爱币 +1 热心值 +1 收起 理由
爱飞的猫 + 1 + 1 热心回复!

查看全部评分

mirrorszyp 发表于 2024-3-14 12:20
BeanUtils好像是使用的反射来做的拷贝,效率似乎不太高。同包的使用cglib来做拷贝的BeanCopier会快很多,不过对嵌套对象它就无可奈何了。
[Java] 纯文本查看 复制代码
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;


/** 存放拷贝过的对象的拷贝器 */
private static final Map<String, BeanCopier> CACHE_MAP = new ConcurrentHashMap<>();

public static void copyProperties(Object source, Object target) {
	if (ObjectUtils.isEmpty(source)) {
		return;
	}

	BeanCopier copier = getBeanCopier(source.getClass(), target.getClass());
	copier.copy(source, target, null);
}

private static BeanCopier getBeanCopier(Class<?> sourceClazz, Class<?> targetClazz) {
	final String key = generatorKey(sourceClazz, targetClazz);
	final BeanCopier copier=Optional.ofNullable(CACHE_MAP.get(key)).orElseGet(() ->  BeanCopier.create(sourceClazz, targetClazz, false));
	CACHE_MAP.put(key, copier);
	return
}

免费评分

参与人数 1吾爱币 +1 热心值 +1 收起 理由
爱飞的猫 + 1 + 1 热心回复!

查看全部评分

uliaxs0n 发表于 2024-3-14 11:32
Malom 发表于 2024-3-14 11:50
如果不考虑性能的话,也可以使用hutool的 BeanUtil.copyToList() 方法,里面源码跟楼主写的基本差不多
暗黑惟我独尊 发表于 2024-3-14 12:05
不是都用mapstuct了么
Chaoasis 发表于 2024-3-14 12:24
spring自带的工具类不好吗
jkln123 发表于 2024-3-14 13:10
感谢分享
Alfie430 发表于 2024-3-14 13:45
感谢分享
lyshy 发表于 2024-3-14 14:48
点赞,非常好用,解决了我的开发问题
caojian1624 发表于 2024-3-14 14:50
大佬厉害谢谢分享学习
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止灌水或回复与主题无关内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-5-11 19:48

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表