简体   繁体   中英

java: super.clone() with Jackon ObjectMapper

So I understand when implementing the clone() method, that you should first call super.clone() so the (potential) super class can do its thing and then do your own cloning. This all makes sure that not variables from the superclass are list / not cloned.

What now if I use Jacksons ObjectMapper to do the cloning:
return objectMapper.readValue(objectMapper.writeValueAsString(this), Mail.class);
I decided to do this as my object ( Mail ) was already fully convertible to and from json which is basically cloning anyways.
In this case calling super.clone() is useless right? Jackson will make a copy of the super variables anyways when it is set up that way so the result of super.clone() doesn't do anything.

Am I missing somthing here?

Greets,
Chris

In this case calling super.clone() is useless right?

Not quiet. Jackson will do everything behind the scenes to correctly instantiate your object but only based on the public fields or those which you've configured to be serializable to JSON. Information about the private fields will be lost .

class A {
   public int x = 10;
   private int y = 100; // this info will be lost when cloning with Jackson
}

While this method is perfectly workable on small projects. I think, it will generate too much overhead if you use it as a clone method on a large one. Too much deserealisation and serialisation can get expensive.

You should consider using the proxy pattern to implement cloning in java. This can also help.

Java's clone method and Jackson are not related in any way. So you do not even need to implement a clone method.

Serializing and deserializing objects has always been a common approach to copy objects. Just keep in mind that it comes with downsides as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM