Java: recommended solution for deep cloning/copying an instance

后端 未结 9 2371
半阙折子戏
半阙折子戏 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:00

    Use XStream toXML/fromXML in memory. Extremely fast and has been around for a long time and is going strong. Objects don't need to be Serializable and you don't have use reflection (although XStream does). XStream can discern variables that point to the same object and not accidentally make two full copies of the instance. A lot of details like that have been hammered out over the years. I've used it for a number of years and it is a go to. It's about as easy to use as you can imagine.

    new XStream().toXML(myObj)
    

    or

    new XStream().fromXML(myXML)
    

    To clone,

    new XStream().fromXML(new XStream().toXML(myObj))
    

    More succinctly:

    XStream x = new XStream();
    Object myClone = x.fromXML(x.toXML(myObj));
    

提交回复
热议问题