有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

这里需要可克隆的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;
    }
}

共 (3) 个答案

  1. # 1 楼答案

    你可以阅读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.

    但是,您没有以正确的方式使用clone()方法。看看这个wiki page

  2. # 2 楼答案

    这里不需要Cloneable

    这是因为clone()的实现实际上并没有克隆对象。在Java中,克隆特别意味着使用Object.clone(),这会让JVM产生复制对象的魔力。虽然你的代码做了一些类似于克隆的事情(更好的是,IMHO——它避免使用魔法),但它不是真正的克隆

    但是,不知道这一点,所以它担心您可能正试图克隆一个非Cloneable对象

    这里的一个解决方案可能是将您的方法重命名为其他方法(copy()),所以它看起来不是克隆

  3. # 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()的文档)

    超级。克隆调用将抛出CloneNotSupportedException