Java: recommended solution for deep cloning/copying an instance

后端 未结 9 2243
半阙折子戏
半阙折子戏 2020-11-22 01:28

I\'m wondering if there is a recommended way of doing deep clone/copy of instance in java.

I have 3 solutions in mind, but I can have miss some, and I\'d like to ha

相关标签:
9条回答
  • 2020-11-22 02:08

    Since version 2.07 Kryo supports shallow/deep cloning:

    Kryo kryo = new Kryo();
    SomeClass someObject = ...
    SomeClass copy1 = kryo.copy(someObject);
    SomeClass copy2 = kryo.copyShallow(someObject);
    

    Kryo is fast, at the and of their page you may find a list of companies which use it in production.

    0 讨论(0)
  • 2020-11-22 02:11

    For deep cloning (clones the entire object hierarchy):

    • commons-lang SerializationUtils - using serialization - if all classes are in your control and you can force implementing Serializable.

    • Java Deep Cloning Library - using reflection - in cases when the classes or the objects you want to clone are out of your control (a 3rd party library) and you can't make them implement Serializable, or in cases you don't want to implement Serializable.

    For shallow cloning (clones only the first level properties):

    • commons-beanutils BeanUtils - in most cases.

    • Spring BeanUtils - if you are already using spring and hence have this utility on the classpath.

    I deliberately omitted the "do-it-yourself" option - the API's above provide a good control over what to and what not to clone (for example using transient, or String[] ignoreProperties), so reinventing the wheel isn't preferred.

    0 讨论(0)
  • 2020-11-22 02:15

    I'd recommend the DIY way which, combined with a good hashCode() and equals() method should be easy to proof in a unit test.

    0 讨论(0)
提交回复
热议问题