What is wrong with this clone()?

前端 未结 9 2017
梦如初夏
梦如初夏 2020-12-09 23:00

I have written this clone method for when the parent of the Employee class is abstract and the clone() method in the parent class is abstract.I wanted to copy the primitive

相关标签:
9条回答
  • 2020-12-09 23:21

    Basically in order to have a properly cloneable object is enough to have a public clone() method implemented in that class.

    The Cloneable interface is a marker interface used to signal to the VM that it's safe to implement the default protected clone() method as a field by field copy.

    In order to properly implement the clone method for a class you should do declare a public method clone like this().

    public Object clone() {
       return super.clone();
    }
    

    A good working implementationk will create a new object and properly assign the fields as the business logic reaquires:

    public Object clone() {
       CurrentClass newObject = new CurrentClass();
    
       newObject.field1 = this.field1; // for simple types: int, long, etc
       newObject.referenceField = this.referenceField.clone(); // for agregate objects or references.
       return newObject;
    }
    

    The conclusion: declare a public clone method. If you want to have the default implementation as a field by field copy call super and mark the class as Cloneable If you want only custom cloning you can ignore the Cloneable mark.

    0 讨论(0)
  • 2020-12-09 23:23

    I think the current green answer is bad , why you might ask?

    • It adds a lot of code
    • It requires you to list all fields to be copied and do this
    • This will not work for Lists when using clone() (This is what clone() for HashMap says: Returns a shallow copy of this HashMap instance: the keys and valuesthemselves are not cloned.) so you end up doing it manually (this makes me cry)

    Oh and by the way serialization is also bad, you might have to add Serializable all over the place (this also makes me cry).

    So what is the solution:

    Java Deep-Cloning library The cloning library is a small, open source (apache licence) java library which deep-clones objects. The objects don't have to implement the Cloneable interface. Effectivelly, this library can clone ANY java objects. It can be used i.e. in cache implementations if you don't want the cached object to be modified or whenever you want to create a deep copy of objects.

    Cloner cloner=new Cloner();
    XX clone = cloner.deepClone(someObjectOfTypeXX);
    

    Check it out at http://code.google.com/p/cloning/

    0 讨论(0)
  • 2020-12-09 23:29

    You should simply write

    return super.clone(); 
    

    in your clone method and implement the Clonable interface.

    0 讨论(0)
提交回复
热议问题