克隆可变成员
我有一个 SBContainer
类,它有一个 StringBuffer
成员 mySB
。我正在像这样为 SBContainer
实现 Cloneable
-
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;
}
}
现在,我为 MyContainer
创建一个对象 sbc1
,它是克隆 <代码>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);
}
}
编辑: 输出是:这是一个测试字符串...附加了
所以,我尝试像这样克隆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
的类的可变成员?
谢谢。
I have a class SBContainer
which has a StringBuffer
member mySB
. I am implementing Cloneable
for SBContainer
like this -
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;
}
}
Now, I create an object sbc1
for MyContainer
and it's clone sbc2
. It looks like the container mySB
is not cloned; and sbc1.mySB
and sbc2.mySB
are pointing to the same StringBuffer
object. I tested using the following class -
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);
}
}
EDIT:
The output was: This is a test string ...something appended
So, I tried to clone mySB
like this -
cloned.mySB = (StringBuffer)mySB.clone();
...and I get this error -
SBContainerTest.java:8: clone() has protected access in java.lang.Object
cloned.mySB = (StringBuffer)mySB.clone();
^
1 error
So, how can I achieve this? How can I clone a mutable member of a class which implements Cloneable
?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
StringBuffer
不可Cloneable
,因此您必须手动克隆它。我建议在您的clone
方法中进行类似的操作:StringBuffer
is notCloneable
, so you'll have to clone it manually. I suggest something like this in yourclone
method: