我正在问一个关于如何在Java中创建不可变对象的基础问题。
所以我有一个来自第三方的Address类,它没有继承任何Cloneable接口且是可变的类。它看起来像这样:
public class Address {
private String city;
private String address;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
现在我有另一个不可变类,称为Person,它实现了Cloneable接口,并覆盖了clone方法。该类如下所示:
public class Person implements Cloneable {
private String name;
private Address address;
public Person() {
}
public Person(String name, Address address) {
this.name = name;
this.address = address;
//this.address = (Address) address.clone();
}
public String getName() {
return name;
}
@Override
protected Object clone() throws CloneNotSupportedException {
Person person = (Person) super.clone();
return super.clone();
}
public Address getAddress() {
return address;
}
@Override
public String toString() {
return "name:" + name + ", address" + address.getAddress() + ", city="
+ address.getCity();
}
}
现在我的问题是,我肯定可以克隆Person类对象,但是如何克隆address类实例?我也读过一些关于浅克隆和深克隆的文章。但是我不明白如何使用第三方API进行深度克隆。如果我对克隆有一些误解,请纠正我。
Address
类非常简单,因此您可以创建自己的类来扩展Address
并实现Cloneable
。话虽如此,我在这里同意Raedwald的观点。请查看SO上的此答案:https://dev59.com/R3NA5IYBdhLWcg3wKai3#1067437 - Chthonic Projectclone()
方法目前总是返回super.clone()
。请改用return person
! - slartidan