简体   繁体   English

在 Java 中使用序列化实现克隆方法是一种好习惯吗?

[英]Is it good practice in Java to implement the clone method using serialization?

I saw several tutorials online where serialization and subsequent deserialization is used to implement deep cloning in Java.我在网上看到了几个教程,其中使用序列化和后续反序列化在 Java 中实现深度克隆。 My feeling is, that this is a solution that is fast to implement and therefore widespread but might have caveats that I currently don't see.我的感觉是,这是一个可以快速实施并因此广泛使用的解决方案,但可能有我目前看不到的警告。

Is that way of implementing clone() good style?这种实现clone()方式是好风格吗? Isn't it slow?是不是很慢? Should deep cloning really be done that way?深度克隆真的应该那样做吗? What better ways exist?有什么更好的方法?

Is it good practice in Java to implement the clone method using serialization?在 Java 中使用序列化实现克隆方法是一种好习惯吗?

If you use serialization to clone an object you have to necessarily unserialize the serialized object to create the cloned object.如果您使用序列化来克隆对象,则必须对序列化对象进行反序列化以创建克隆对象。 It makes two operations where the second seems be an overhead as it should not be performed if you implement the cloning operation at the hand or with a mapper API (ex: SpringBean, Common apache, ModelMapper, Dozzer...).它进行了两个操作,其中第二个操作似乎是开销,因为如果您在手边或使用映射器 API(例如:SpringBean、Common apache、ModelMapper、Dozzer...)实现克隆操作,则不应执行它。
So it has without no doubt an impact on the performance.所以毫无疑问,它对性能有影响。 If you do this processing very occasionally, I don't think that it should be a problem (even if it seems to be a useless overhead and you have alternative ways) but if you use it often I think that it may have a cost.如果您非常偶尔地进行此处理,我认为这应该不是问题(即使它似乎是无用的开销并且您有其他方法)但如果您经常使用它,我认为它可能会产生成本。

Besides, why implementing Clonable to clone an object by using serialization instead of forgetting Cloneable that is a clumsy API and using directly the deserialization mechanism ?此外,为什么要实现Clonable使用序列化来克隆对象,而不是忘记Cloneable这个笨拙的 API 并直接使用deserialization机制?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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