开发者

Copy object into another

开发者 https://www.devze.com 2022-12-25 03:19 出处:网络
Is there a generic way to achieve copying an existing object into another? Assume MyObj has an id and name fields.Like this:

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.


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


Use copy constructor:

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

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


Object.clone() & interface Cloneable


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


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.


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();
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消