Copy an object in Java

后端 未结 7 581
伪装坚强ぢ
伪装坚强ぢ 2020-12-09 03:41

I have an object that I need to copy in Java. I need to create a copy and run some tests on it without changing the original object itself.

I assumed that I needed t

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-09 04:19

    Some options:

    • You can implement Cloneable for your object and put clone() method as public. See full explanation here: http://www.cafeaulait.org/course/week4/46.html
      However, this produces a shallow copy and might be not something you want.
    • You can serialize and deserialize your object. You will need to implement Serializable interface for the object and all its fields.
    • You can use XStream to perform serialization via XML - you won't have to implement anything here.

提交回复
热议问题