推荐课程
1、通过继承Cloneable接口,重写clone方法实现深克隆
3、第三方工具类实现深克隆,克隆对象需继承Serializable接口
3.1、Apache Commons Lang的SerializationUtils.clone方法
@Data
@AllArgsConstructor
@ToString
public class User implements Cloneable{
private String name;
private int age;
private House house;
@Override
protected User clone() throws CloneNotSupportedException {
User user = (User) super.clone();
user.setHouse(house.clone());
return user;
}
}
@Data
@AllArgsConstructor
@ToString
public class House implements Cloneable{
private String location;
private double price;
@Override
protected House clone() throws CloneNotSupportedException {
return (House) super.clone();
}
}public static void main(String[] args) {
House house = new House("市区", 58955);
User user = new User("张三", 18, house);
User cloneUser = user.clone();
}
克隆对象需继承Serializable接口
@Data
@AllArgsConstructor
@ToString
public class House implements Serializable {
private String location;
private double price;
}
@Data
@AllArgsConstructor
@ToString
public class User implements Serializable {
private String name;
private int age;
private House house;
}
@SneakyThrows
public static void main(String[] args) {
House house = new House("市区", 58955);
User user = new User("张三", 18, house);
//序列化
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
objectOutputStream.writeObject(user);
//反序列化
ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
User cloneUser = (User)objectInputStream.readObject();
}
@Data
@AllArgsConstructor
@ToString
public class House implements Serializable {
private String location;
private double price;
}
@Data
@AllArgsConstructor
@ToString
public class User implements Serializable {
private String name;
private int age;
private House house;
}
3.1、Apache Commons Lang的SerializationUtils.clone方法
org.apache.commons
commons-lang3
public static void main(String[] args) {
House house = new House("市区", 58955);
User user = new User("张三", 18, house);
User cloneUser = SerializationUtils.clone(user);
}
3.2、Gson工具类
com.google.code.gson
gson
2.8.5
@SneakyThrows
public static void main(String[] args) {
House house = new House("市区", 58955);
User user = new User("张三", 18, house); Gson gson = new Gson();
//将对象序列化为json字符串
String userStr = gson.toJson(user);
//然后将字符串反序列化为对象
User cloneUser = gson.fromJson(userStr, User.class);
}
3.3、FastJson工具类
com.alibaba
fastjson
1.2.78
@SneakyThrows
public static void main(String[] args) {
House house = new House("市区", 58955);
User user = new User("张三", 18, house);
//将对象序列化为json字符串
String userStr = JSON.toJSONString(user);
//然后将字符串反序列化为对象
User cloneUser = JSON.parseObject(userStr, User.class);
}
以上内容为个人学习理解,如有问题,欢迎在评论区指出。
部分内容截取自网络,如有侵权,联系作者删除。