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
?
Just follow as below:
and wherever you want to get another object, simple perform cloning. e.g:
Deep Cloning is your answer, which requires implementing the
Cloneable
interface and overriding theclone()
method.You will call it like this
DummyBean dumtwo = dum.clone();
Pass the object that you want to copy and get the object you want:
Now parse the
objDest
to desired object.Happy Coding!