我的班级SBContainer
有StringBuffer
成员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.mySB
和sbc2.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
的类的可变成员?
感谢。
答案 0 :(得分:2)
StringBuffer
不是Cloneable
,因此您必须手动克隆它。我在你的clone
方法中提出了类似的建议:
public Object clone() throws CloneNotSupportedException {
SBContainer cloned = (SBContainer)super.clone();
cloned.mySB = new StringBuffer(this.mySB);
return cloned;
}