Do you need to clone?

Findbugs gives me the public GsmSignalStrength clone()following warning: The class defines clone () but does not implement Cloneable.

Why should I implement Cloneable? Is it because of the shallow and deep copy? I have to apologize for my poor Java skills, but I'm new to Java.

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;
    }
}
+3
source share
3 answers

Cloneable not required here.

This is because your implementation clone()does not actually clone the object. In Java, cloning specifically means a use Object.clone()that makes the JVM magic to copy an object. Although your code does something like the equivalent of cloning (and better, IMHO - it avoids the use of magic), it's not true cloning.

However , , , Cloneable.

- (copy()?), .

+2

.

Cloneable Object.clone(), .

, Cloneable, CloneNotSupportedException.

clone() . wiki.

+3

public GsmSignalStrength clone()
{
    try{
    GsmSignalStrength clonedValue = (GsmSignalStrength )super.clone();

    this.copyTo(clonedValue);
    return clonedValue;
    }catch(CloneNotSupportedException e){thrown new RunTimeException(e);}

}

(, - GsmSignalStrength, Object.clone())

super.clone CloneNotSupportedException

+1
source

All Articles