当在网络中搜索多种可能性时如何制作对象的深层副本时,我发现solution声称可以解决许多问题,例如,clone()方法不可能克隆final字段。该解决方案结合使用clone()里面执行受保护的拷贝构造函数,基本上是这样的(例如,从引用的页面复制):使用新的关键字和复制构造函数代替super.clone的Java克隆()方法
public class Person implements Cloneable
{
private final Brain brain; // brain is final since I do not want
// any transplant on it once created!
private int age;
public Person(Brain aBrain, int theAge)
{
brain = aBrain;
age = theAge;
}
protected Person(Person another)
{
Brain refBrain = null;
try
{
refBrain = (Brain) another.brain.clone();
// You can set the brain in the constructor
}
catch(CloneNotSupportedException e) {}
brain = refBrain;
age = another.age;
}
public Object clone()
{
return new Person(this);
}
…
}
的Brain的clone()方法可以以类似的方式来实现。
基于documentation of the clone() method,似乎这个方法的所有“契约”不是绝对的要求,而且“返回的对象应该通过调用super.clone()获得”仅仅是一个约定。
那么,这个实现实际上是不正确的?为什么?
如果它是正确的,为什么它没有成为设计模式?这有什么缺点?
感谢,切赫
2013-04-03
Posa
+0
我不明白为什么不简单地使用“新人(this.brain,this.age)”(如果属性是最终的)或“新人(this.brain.clone(),this.age)在其他case –
+0
clone()'已经足够的了,你应该只是在任何地方使用拷贝构造函数,并且完全停止编写'clone'方法 –
+0
我从来没有理解过为什么你需要它们,你需要在C++中拷贝构造函数,因为编译器生成调用有时甚至需要自己编写它们,最终这是因为默认的C++参数语义是object-by的值,但在近16年的Java中,我从未使用clone()或copy构造函数任何严肃的代码 –