Wednesday, April 11, 2012

Is Cloneable needed here?

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;
}
}




2 comments:

  1. This is because your implementation of clone() does not actually clone the object. In Java, cloning specifically means using Object.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-Cloneable object.

    One solution here might be to rename your method to something else (copy()?), so it doesn't appear to be a clone.

    ReplyDelete
  2. You can read the documentation.

    A class implements the Cloneable interface to indicate to the Object.clone() method that it is legal for that method to make a field-for-field copy of instances of that class.

    Invoking Object's clone method on an instance that does not implement the Cloneable interface results in the exception CloneNotSupportedException being thrown.

    However you are not using clone() method in the right way. Look at this wiki page.

    ReplyDelete