这里需要可克隆的java吗?
Findbugs给了我以下警告: 类定义clone(),但不实现Cloneable
为什么我必须实现Cloneable?是因为浅拷贝和深拷贝吗?我不得不为我糟糕的Java技能道歉,但我是一个Java新手
这是我的代码:
class GsmSignalStrength
{
static final byte SIGNAL_STRENGTH_UNKNOWN = 99;
static final byte SIGNAL_STRENGTH_1 = 1;
static final byte SIGNAL_STRENGTH_2 = 2;
static final byte SIGNAL_STRENGTH_3 = 3;
static final byte SIGNAL_STRENGTH_4 = 4;
static final byte SIGNAL_STRENGTH_5 = 5;
/* Constructors */
GsmSignalStrength(byte signalStrength)
{
initClassVars(signalStrength);
}
GsmSignalStrength()
{
initClassVars(SIGNAL_STRENGTH_UNKNOWN);
}
GsmSignalStrength(byte[] serializedData, IntClass deserializationIndex)
{
initClassVars(SIGNAL_STRENGTH_UNKNOWN);
setClassProperties(serializedData, deserializationIndex);
}
byte value;
/* Methods */
public void copyTo(GsmSignalStrength destination)
{
destination.value = this.value;
}
public GsmSignalStrength clone()
{
GsmSignalStrength clonedValue = new GsmSignalStrength();
this.copyTo(clonedValue);
return clonedValue;
}
private void initClassVars(byte signalStrength)
{
this.value = signalStrength;
}
}
# 1 楼答案
你可以阅读documentation
但是,您没有以正确的方式使用
clone()
方法。看看这个wiki page# 2 楼答案
这里不需要
Cloneable
这是因为
clone()
的实现实际上并没有克隆对象。在Java中,克隆特别意味着使用Object.clone()
,这会让JVM产生复制对象的魔力。虽然你的代码做了一些类似于克隆的事情(更好的是,IMHO——它避免使用魔法),但它不是真正的克隆但是,findbugs不知道这一点,所以它担心您可能正试图克隆一个非
Cloneable
对象这里的一个解决方案可能是将您的方法重命名为其他方法(
copy()
),所以它看起来不是克隆# 3 楼答案
如果将克隆实现为
(如果你要将GsmSignalStrength子类化,你需要根据Object.clone()的文档)
超级。克隆调用将抛出CloneNotSupportedException