3

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;
}
jihor
  • 2,478
  • 14
  • 28
eastwater
  • 4,624
  • 9
  • 49
  • 118

2 Answers2

6

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • `Since you must implement clone()...` In general, this is not a requirement since there is a default `clone()` method in `Object`. For this particular requirement, then "must" is correct. – Code-Apprentice Jan 30 '18 at 17:29
  • 1
    @Code-Apprentice You are right, I need to qualify this statement, because a class could legitimately keep `clone()` protected for internal use. Thanks for the comment! – Sergey Kalinichenko Jan 30 '18 at 17:31
4

There is no specific annotation that can do that to my knowledge.

You could override the Object#clone method, and selectively set the non-cloneable fields' values to null on the returned Object after casting.

The cloned object will still feature the field since it should be casted explicitly to the same class, but that value will be null.

Mena
  • 47,782
  • 11
  • 87
  • 106