Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy object into another

Tags:

java

Is there a generic way to achieve copying an existing object into another?

Assume MyObj has an id and name fields. Like this:

MyObj myObj_1 = new MyObj(1, "Name 1");
MyObj myObj_2 = new MyObj(2, "Name 2");

Instead of

myObj_2.setName(myObj_1.getName()) // etc for each field

do something as following:

myObj_2.copyFrom(myObj_1)

so that they are different instances, but have equal properties.

like image 940
EugeneP Avatar asked Mar 29 '10 09:03

EugeneP


People also ask

Can an object be copied?

There are several ways to copy an object, most commonly by a copy constructor or cloning. Copying is done mostly so the copy can be modified or moved, or the current value preserved. If either of these is unneeded, a reference to the original data is sufficient and more efficient, as no copying occurs.

How do I copy an object to another object in TypeScript?

To create a deep copy of an object in TypeScript, install and use the lodash. clonedeep package. The cloneDeep method recursively clones a value and returns the result. The cloneDeep method returns an object of the correct type.


1 Answers

The convention is to do this at construction time with a constructor that takes one parameter of its own type.

MyObj myObj_2 = new MyObj(myObj_1);

There is no Java convention to overwrite the existing properties of an object from another. This tends to go against the preference for immutable objects in Java (where properties are set at construction time unless there is a good reason not to).

Edit: regarding clone(), many engineers discourage this in modern Java because it has outdated syntax and other drawbacks. http://www.javapractices.com/topic/TopicAction.do?Id=71

like image 93
Jim Blackler Avatar answered Oct 19 '22 23:10

Jim Blackler