Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java how to make a field not cloneable

Tags:

java

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;
}
like image 612
eastwater Avatar asked Jun 28 '26 14:06

eastwater


2 Answers

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.

like image 131
Sergey Kalinichenko Avatar answered Jul 01 '26 02:07

Sergey Kalinichenko


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.

like image 38
Mena Avatar answered Jul 01 '26 04:07

Mena



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!