Anand
Anand

Reputation: 21310

Setting all properties from Java bean to another

Suppose I have a Java bean, say Employee, with some properties.
I want to copy all the properties of Employee to another instance of the same Java bean.

One solution is to get the properties using getter and set it to the another instance. But that will be time consuming if there are many properties in the POJO.

Is there any quicker way to achieve the same?

Upvotes: 2

Views: 590

Answers (3)

Mario
Mario

Reputation: 3313

If you have just a few classes to support the cloning, then overriding the clone() could be the fastest solution. Otherwise, if you need a generic solution, don't reinvent the wheel:

Upvotes: 0

NimChimpsky
NimChimpsky

Reputation: 47280

Object.clone performs a shallow copy, so you might be better off rolling your own copy constructor :

public class Dog {
    public final List<String> names;
    public int age;
    public int weight;

    public Dog() {
        names = new ArrayList<String>();
    }

    protected Dog(Dog original) {
        names = new ArrayList<String>(original.names);
        age = original.age;
        weight = original.weight;
    }

    public Dog copy() {
        return new Dog(this);
    }
}

kudos

Upvotes: 0

Augusto
Augusto

Reputation: 29827

As assylias mentioned, the time that it takes to copy a bean is very small. Unless you need to do this a few million times a second.

The important bit (I think) is to reduce the amount of silly code, so to "copy" a bean, you can make it extend Clonable, and the JVM will do the rest. You just need to call bean.clone().

Another more flexible option is to use Apache BeanUtils, which can copy between objects using reflection.

Upvotes: 1

Related Questions