EugeneP
EugeneP

Reputation: 12003

Copy object into another

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.

Upvotes: 6

Views: 18555

Answers (6)

MANTU KUMAR
MANTU KUMAR

Reputation: 1

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 all the content of previous object into the newly created object. Before using the clone() method you have 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();
        }
    }
}

Upvotes: 0

Boris Pavlović
Boris Pavlović

Reputation: 64632

Use copy constructor:

public class YourObject {
  private String name;
  private int age;

  public YourObject(YourObject other) {
     this.name = other.name;
     this.age = other.age;
  }
}

Upvotes: 7

codymanix
codymanix

Reputation: 29468

You can use introspection to automate the implementation of your clone routines, so you can be safe you do not forget to copy some fields.

Upvotes: 0

Jim Blackler
Jim Blackler

Reputation: 23169

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

Upvotes: 8

Dishayloo
Dishayloo

Reputation: 390

The clone()-method is for exactly this job.

Upvotes: 0

Related Questions