Consider the code below:
DummyBean dum = new DummyBean();
dum.setDummy("foo");
System.out.println(dum.getDummy()); // prints 'foo'
DummyBean dumtwo = dum;
System.out.println(dumtwo.getDummy()); // prints 'foo'
dum.setDummy("bar");
System.out.println(dumtwo.getDummy()); // prints 'bar' but it should print 'foo'
So, I want to copy the dum
to dumtwo
and change dum
without affecting the dumtwo
. But the code above is not doing that. When I change something in dum
, the same change is happening in dumtwo
also.
I guess, when I say dumtwo = dum
, Java copies the reference only. So, is there any way to create a fresh copy of dum
and assign it to dumtwo
?
You can deep copy automatically with XStream, from http://x-stream.github.io/:
Add it to your project (if using maven)
Then
With this you have a copy without the need to implement any cloning interface.
Why is there no answer for using Reflection API?
It's really simple.
EDIT: Include child object via recursion
Yes, you are just making a reference to the object. You can clone the object if it implements
Cloneable
.Check out this wiki article about copying objects.
Refer here: Object copying
In the package
import org.apache.commons.lang.SerializationUtils;
there is a method:Example:
You can try to implement
Cloneable
and use theclone()
method; however, if you use the clone method you should - by standard - ALWAYS overrideObject
'spublic Object clone()
method.