Aditya Bahuguna
Aditya Bahuguna

Reputation: 647

How to deep copy an object to another class object with same fields?

I have two java classes as follows

public class A implements Serializable {

    private String name;
    private List<String> nameList;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public List<String> getNameList() {
        return nameList;
    }
    public void setNameList(List<String> nameList) {
        this.nameList = nameList;
    }   
}

public class B implements Serializable {

    private String name;
    private List<String> nameList;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public List<String> getNameList() {
        return nameList;
    }
    public void setNameList(List<String> nameList) {
        this.nameList = nameList;
    }   
}

Now I have an object of class A, Aobj, with both the fields initialized. I am using BeanUtils.copyProperties(Bobj, Aobj), but only the name field value is copied into the Bobj however Bobj.nameList is null. Is there a way to deep copy a object so that it copies all the fields including Collections like List, Map etc.

I somewhere heard about Dozer, not sure if that is meant for this purpose.

Upvotes: 1

Views: 1654

Answers (1)

Michael Gantman
Michael Gantman

Reputation: 7808

It is a bit strange that you have 2 different classes that are absolutely identical. But regardless, in order to deep copy one to another just write a 2 static methods in some Util class. One method will take class A and return class B and another will take B and return class A. Do your deep copying by yourself. Also, you can create class C that is the same as your classes A and B and then make your classes A and B just empty classes each extending C. It would give you the same structure, but would make your copying logic easier as you can just work with both A and B as instances of C.

Upvotes: 1

Related Questions