Alex Rivera | Logout

Copy an object in Java

Asked 2009-01-24T10:40:47.217
21

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 to use the clone() method, but this is protected. Having done some research on the net, I can see that this can be overriden with a public method in my class. But I cannot find an explanation on how to do this. How could this be done?

Also, is this the best way of achieving what I need?

Edit
Report

2 Answers

14

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.
answered 2009-01-24T10:49:57.900
9

For test code Serialization is maybe the safest answer, especially if the object is already Serializable try Apache Commons SerializationUtils for an implementation.

answered 2009-01-24T11:04:03.833

Your Answer