我有:
personne类在其字段中使用Adress类。
所以我想要的是选择:
修改克隆的人员地址
这是我的克隆方法:
Object o = null;
try {
o = super.clone();
} catch(CloneNotSupportedException cnse) {
cnse.printStackTrace(System.err);
}
return o;
}
但原来的Person类不能访问 Cloned Person class Adress field。
请给我一个提示。
答案 0 :(得分:0)
试试这个:
public Personne clone()
{
Personne o;
try {
o = (Personne)super.clone();
o.adresse = null;//or just change it however you want here.
return o;
} catch(CloneNotSupportedException cnse) {
cnse.printStackTrace(System.err);
throw new RuntimeException();
}
}
确保Personne的属性是不可变的,如果它们不是你应该为主要clone()mehtod中单独不可变的每个属性调用clone()方法。
答案 1 :(得分:0)
好的伙计们,所以在我理解的帮助下。 覆盖clone()方法的可能性是让opurtunity修改克隆类的字段。作为建议的解决方案,将类的Adress字段重置为NULL。 然后我创建了一个setter,它提供了修改克隆地址字段的选项。
@Override
public Personne clone()
{
Personne o;
try {
o = (Personne)super.clone();
o.adresse = null;
return o;
} catch(CloneNotSupportedException cnse) {
cnse.printStackTrace(System.err);
throw new RuntimeException();
}
}
// setter pour l adresse du Clone :
public void setAdresseClone(Adresse a){
this.clone().adresse = a;
}