copy后的两个对象互不影响,可理解为深层拷贝
- 测试入口
public static void main(String[] args) {
TestDto a = new TestDto("a");
TestDto b1 = new TestDto("b1");
TestDto b = new TestDto("b", b1);
List<TestDto> list = new ArrayList<>(Arrays.asList(a, b));
// List<TestDto> listCopy = EntityHelper.copyByStream(list);
List<TestDto> listCopy = EntityHelper.copyByJson(list, new TypeReference<List<TestDto>>() {
});
// listCopy.removeIf(x -> x.getName().equals("a"));
for (TestDto demo : listCopy) {
if (demo.getDtoList() != null) demo.getDtoList().removeIf(x -> x.getName().equals("b1"));
}
System.out.println(list);
// 输出
// [TestDto(name=a, dtoList=null), TestDto(name=b, dtoList=[TestDto(name=b1, dtoList=null)])]
}
2.工具类
/**
* 流的形式copy【复制后两个对象独立】【T必须实现Serializable】
*/
public static <T extends Serializable> List<T> copyByStream(Collection<T> src) {
// 将对象写到流里
try {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo = new ObjectOutputStream(bo);
oo.writeObject(src);
// 从流里读出来
ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
ObjectInputStream oi = new ObjectInputStream(bi);
return new ArrayList<>((Collection<? extends T>) oi.readObject());
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
throw new RuntimeException("copy utils: data copy error");
}
}
/**
* 转json的形式copy【复制后两个对象独立】
*/
public static <T> T copyByJson(T src, TypeReference<T> type) {
// 这里就是简单的ObjectMapping转换了一下
String json = entityToJson(src);
return jsonToEntity(json, type);
}
3.实体类
@Data
public class TestDto implements Serializable {
private String name;
private List<TestDto> dtoList;
public TestDto() {
}
public TestDto(String name) {
this.name = name;
}
public TestDto(String name, TestDto... dtoList) {
this.name = name;
this.dtoList = new ArrayList<>(Arrays.asList(dtoList));
}
}
实测可行,就是copyByJson没法根据泛型来定义TypeReference,这样可以省掉一个传参。然而不行,一直出现map转entity失败的报错,强迫症着实难受。