Findbugs gives me for public GsmSignalStrength clone() following warning:
Class defines clone() but doesn’t implement Cloneable.
Why do I have to implement Cloneable? Is it because of shallow and deep copy? I have to apologize for my bad Java skills, but I’m a Java newbie.
Here is my code:
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;
}
}
Cloneableis not needed here.This is because your implementation of
clone()does not actually clone the object. In Java, cloning specifically means usingObject.clone(), which does JVM magic to copy the object. Although your code does something sort of equivalent to cloning (and better, IMHO – it avoids using magic), it is not true cloning.However, findbugs doesn’t know that, so it’s worried that you might be trying to clone a non-
Cloneableobject.One solution here might be to rename your method to something else (
copy()?), so it doesn’t appear to be a clone.