Search code examples
javaobjectcopyclonejavabeans

How to copy a (JavaBean) object's state into another, existing object?


Image you have a class that looks as follows:

class Foo
{
   public String x;
   public int y;
   public long l;
}

then somewhere we have:

Foo foo1 = new Foo();
foo1.x = "a";
foo1.y = 3;
foo1.l = 2L;

and then somewhere else we have another Foo object whose fields have not been initialized.

Foo foo2 = new Foo();
//foo2 = foo1; 

Given that assigning a reference to the object represented by the variable foo1 to the variable foo2 is not what I want to do here, since I want to preserve the reference to the object represented by foo2, what's the simplest way to copy the state of foo1 to foo2?

In other words, how do I do this automatically?

foo2.x = foo1.x;
foo2.y = foo1.y;
foo2.l = foo1.l;

Solution

  • If Foo was a JavaBean that is if it had proper setters / getters instead of public fields you could use Apache Commons Beanutils.copyProperties(Object dest, Object orig)