javacloneable

java how to make a field not cloneable


For serialization, transient fields will be excluded. Is there any similar keyword for clone? How to exclude a field from clone?

public class Foo implements Cloneable {
    private Integer notInClone;
}

Solution

  • Since you must implement clone() if you want it to be public (it's not part of Cloneable interface, and is protected in the Object) you will have an opportunity to clear out the unwanted fields in your code:

    public Object clone() throws CloneNotSupportedException {
        Foo res = (Foo)super.clone();
        res.notInClone = null;        // Do the cleanup for fields that you wish to exclude
        return res;
    }
    

    Demo.