深copy

方法一,感觉最简单,先转为JSON,后面在转回来一次
同时这也使用对象之间的copy
ArrayList sysUsers = new ArrayList<>();
SysUser sysUser = new SysUser();
sysUser.setEmail("11");
sysUsers.add(sysUser);
SysUser sysUser1 = new SysUser();
sysUser1.setEmail("12");
sysUsers.add(sysUser1);
List sysUsers1 = JSON.parseArray(JSON.toJSONString(sysUsers), SysUser.class);
sysUsers.remove(1);
System.out.println(JSON.toJSONString(sysUsers));
System.out.println(JSON.toJSONString(sysUsers1));

方法二,直接序列化,

AddressClone address = new AddressClone("小区1", "小区2");
        UserClone user = new UserClone("小李", address);
        UserClone copyUser = user.clone();
        user.getAddress().setAddress1("小区3");
        // false
        System.out.println(user == copyUser);

第三种方法 推荐

Hessian 是动态类型、二进制、紧凑的,并且可跨语言移植的一种序列化框架。Hessian 协议要比 JDK、JSON 更加紧凑,性能上要比 JDK、JSON 序列化高效很多,而且生成的字节数也更小

Student student = new Student(); 
student.setNo(101);  
student.setName("HESSIAN"); 
//把student对象转化为byte数组
ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
Hessian2Output output = new Hessian2Output(bos); 
output.writeObject(student); 
output.flushBuffer(); 
byte[] data = bos.toByteArray(); 
bos.close(); 
//把刚才序列化出来的byte数组转化为student对象
ByteArrayInputStream bis = new ByteArrayInputStream(data); 
Hessian2Input input = new Hessian2Input(bis); 
Student deStudent = (Student) input.readObject(); 
input.close(); 
System.out.println(deStudent);
 

你可能感兴趣的:(java,开发语言)