克隆一个可变成员

时间:2011-06-22 14:05:43

标签: java clone

我的班级SBContainerStringBuffer成员mySB。我正在为此Cloneable实施SBContainer -

SBContainer implements Cloneable {
    public StringBuffer mySB;
    public SBContainer() {
        mySB = new StringBuffer("This is a test string");
    }
    public Object clone() throws CloneNotSupportedException {
        SBContainer cloned = (SBContainer)super.clone();
        return cloned;
    }
}

现在,我为sbc1创建了一个对象MyContainer,它是克隆sbc2。看起来容器mySB没有被克隆;并且sbc1.mySBsbc2.mySB指向同一个StringBuffer对象。我使用以下类测试 -

public class SBContainerTest {
    public static void main(String[] args) {
        SBContainer sbc1 = new SBContainer();
        SBContainer sbc2 = null;
        try {
            sbc2 = (SBContainer)sbc1.clone();
        } catch(CloneNotSupportedException e) {
            e.printStackTrace();
        }
        sbc1.mySB.append(" ...something appended");
        System.out.println(sbc2.mySB);
    }
}

修改 输出为:This is a test string ...something appended

所以,我试图像这样克隆mySB -

cloned.mySB = (StringBuffer)mySB.clone();

...我收到此错误 -

SBContainerTest.java:8: clone() has protected access in java.lang.Object
        cloned.mySB = (StringBuffer)mySB.clone();
                                        ^
1 error

那么,我怎样才能做到这一点?如何克隆实现Cloneable的类的可变成员?

感谢。

1 个答案:

答案 0 :(得分:2)

StringBuffer不是Cloneable,因此您必须手动克隆它。我在你的clone方法中提出了类似的建议:

public Object clone() throws CloneNotSupportedException {
    SBContainer cloned = (SBContainer)super.clone();
    cloned.mySB = new StringBuffer(this.mySB);
    return cloned;
}