是的,按字段复制的字段意味着当它创建新的(克隆的)对象时,JVM会将每个字段的值从原始对象复制到克隆的对象中.不幸的是,这意味着你有一个浅的副本.如果你想要一个深层次的拷贝,你可以覆盖克隆方法.
class Line implements Cloneable {
private Point start;
private Point end;
public Line() {
//Careful: This will not happen for the cloned object
SomeGlobalRegistry.register(this);
}
@Override
public Line clone() {
//calling super.clone is going to create a shallow copy.
//If we want a deep copy,we must clone or instantiate
//the fields ourselves
Line line = (Line)super.clone();
//assuming Point is cloneable. Otherwise we will
//have to instantiate and populate it's fields manually
line.start = this.start.clone();
line.end = this.end.clone;
return line;
}
}
还有一个关于克隆的另一个重要的事情是,克隆对象的构造函数从不被调用(仅复制字段).因此,如果构造函数初始化外部对象,或者使用某些注册表注册此对象,则克隆对象不会发生.
我个人更喜欢不使用Java的克隆.相反,我通常会创建自己的“重复”方法.