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;
}
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;
}
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
.