我正在编写一个类,在该类中我必须使用臭名昭著的“super.clone() 策略”覆盖clone() 方法(这不是我的选择)。
我的代码如下所示:
@Override
public myInterface clone()
{
myClass x;
try
{
x = (myClass) super.clone();
x.row = this.row;
x.col = this.col;
x.color = this.color;
//color is a final variable, here's the error
}
catch(Exception e)
{
//not doing anything but there has to be the catch block
//because of Cloneable issues
}
return x;
}
Run Code Online (Sandbox Code Playgroud)
一切都会好起来的,除了我不能color
在不使用构造函数的情况下初始化,因为它是一个最终变量......有没有办法既使用 super.clone() 又复制最终变量?
由于调用super.clone();
将已经创建所有字段的(浅)副本,无论是否最终,您的完整方法将变为:
@Override
public MyInterface clone() throws CloneNotSupportedException {
return (MyInterface)super.clone();
}
Run Code Online (Sandbox Code Playgroud)
这要求超类也clone()
正确实现(以确保super.clone()
最终到达Object
类。所有字段都将被正确复制(包括最终字段),如果您不需要深层克隆或任何其他特殊功能,则可以使用此然后保证您永远不会clone()
再次尝试实现(原因之一是正确实现它并不容易,从这个问题可以明显看出)。