Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

6
  • Your best option is probably to write a copy constructor yourself, and do MyClass newObj = new MyClass(oldObj);. Other options are to rely on serialization/deserialization or Object.clone but please read Copy Constructor versus Cloning. Commented Jan 22, 2016 at 8:05
  • how can we done this if the object is not serializable Commented Jan 22, 2016 at 8:37
  • Are you controlling the implementation? (Can you modify the code of the class?) Or do you want to deep copy an object from a library? Commented Jan 22, 2016 at 9:19
  • No, I cannot modify the class of the object. I simply want to write a general method that will copy the object passing as a parameter to it. Commented Jan 22, 2016 at 9:49
  • Not possible I'm afraid. Consider what would happen if the object you're trying to copy holds a reference to a singleton object for instance. Commented Jan 22, 2016 at 9:53