I have copied one object into another with help of
BeanUtils.CopyProperties(Src,Dest);
From : package org.springframework.beans;
Now further in logic , with help of iterator I modify the list inside Dest object.
I want src object to be as it is.
But I see a weird behavior. My Src is also getting modified.
What can be the reason ?
Example:
src and Dest have list: [Mango , Apple]
I removed Mango from Dest with help of iteartor.
later I see
Src have [Apple]
Dest have [Apple]
Is it happening because of shallow copy ?
You don't want to copy the List
field but clone it in the new copied object.
BeanUtils.copyProperties(Object source, Object target)
doesn't explicit clearly in its javadoc but it does a shallow copy from a object to another one.
It means that in the target
object, the List
field will reference the same object that which one in the source
object.
So modifying the List
field from the one or the other one object will be reflected in the other.
To create a new List, you should create a new List instance that contains the actual elements in the source List
and assign it to the List
field in the target object.
For example :
MyObject source = ...;
MyObject target = ...;
BeanUtils.copyProperties(source, target);
...
List<String> newList = new ArrayList<>(source.getList());
target.setList(newList);