Copy an object to another

Is there a general way to copy an existing object to another?

Suppose MyObj has id and name fields. Like this:

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

Instead

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

do the following:

 myObj_2.copyFrom(myObj_1) 

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

+6
java
source share
6 answers

The convention is to do this at build time using a constructor that takes one parameter of its type.

MyObj myObj_2 = new MyObj (myObj_1);

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

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

+8
source share

Use copy constructor:

 public class YourObject { private String name; private int age; public YourObject(YourObject other) { this.name = other.name; this.age = other.age; } } 
+7
source share
+4
source share

The clone () method is designed specifically for this task.

0
source share

You can use introspection to automate the implementation of your cloning routines, so you can be safe without forgetting to copy some fields.

0
source share

The clone() method is best suited for these requirements. Whenever the clone() method is called on an object, the JVM will actually create a new object and copy the entire contents of the previous object into the newly created object. Before using the clone() method, you need to implement the Cloneable interface and override the clone() method.

 public class CloneExample implements Cloneable { int id; String name; CloneExample(int id, String name) { this.id = id; this.name = name; } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } public static void main(String[] args) { CloneExample obj1 = new CloneExample(1,"Name_1"); try { CloneExample obj2 = (CloneExample) obj1.clone(); System.out.println(obj2.id); System.out.println(obj2.name); } catch (CloneNotSupportedException e) { e.printStackTrace(); } } } 
0
source share

All Articles