Reputation: 21310
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
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
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);
}
}
Upvotes: 0
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