039.制作CopyUtil封装BeanUtils
1.单个对象的复制
EbookResp ebookResp = new EbookResp();
BeanUtils.copyProperties(ebook, ebookResp);
2.list对象的复制
List<EbookResp> respList = new ArrayList<>(); for (Ebook ebook : ebookList) { EbookResp ebookResp = new EbookResp(); BeanUtils.copyProperties(ebook, ebookResp); EbookResp ebookResp = CopyUtil.copy(ebook, EbookResp.class); respList.add(ebookResp); }
3.制作制作CopyUtil封装BeanUtils
package com.jiawa.wiki.util; import org.springframework.beans.BeanUtils; import org.springframework.util.CollectionUtils; import java.util.ArrayList; import java.util.List; public class CopyUtil { /** * 单体复制 */ public static <T> T copy(Object source, Class<T> clazz) { if (source == null) { return null; } T obj = null; try { obj = clazz.newInstance(); } catch (Exception e) { e.printStackTrace(); return null; } BeanUtils.copyProperties(source, obj); return obj; } /** * 列表复制 */ public static <T> List<T> copyList(List source, Class<T> clazz) { List<T> target = new ArrayList<>(); if (!CollectionUtils.isEmpty(source)){ for (Object c: source) { T obj = copy(c, clazz); target.add(obj); } } return target; } }
//利用工具类进行复制
List<EbookResp> list = CopyUtil.copyList(ebookList, EbookResp.class);