import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeanUtils; import org.springframework.util.CollectionUtils; import java.util.ArrayList; import java.util.List; /** * * @version 1.0.0 * @createTime 2019/11/22 11/52 */ @Slf4j public class BeanCopyUtils { public static <T> T copyBean(Object source,Class<T> target){ assert target != null; T t = null; try { t = target.newInstance(); BeanUtils.copyProperties(source,t); return t; } catch (Exception e) { e.printStackTrace(); } // 抛异常出去,或者返回 null // throw new BusinessException(RespCodeEnum.SYSTEM_ERROR,"BeanCopyUtils copyBean source 转 Class 异常。source:"+ source.toString() + "; target class :" + target); } public static <S,T> List<T> copyList(List<S> sourceList, Class<T> targetObject) { assert targetObject != null; assert !CollectionUtils.isEmpty(sourceList); List<T> targetList = new ArrayList<>(); sourceList.forEach(s ->{ T t = null; try { t = targetObject.newInstance(); } catch (Exception e) { e.printStackTrace(); } BeanUtils.copyProperties(s, t); targetList.add(t); }); return targetList; } }
BeanCopyUtils 实现单个对象,多个对象属性Copy
最新推荐文章于 2024-04-01 23:07:16 发布