I know that BeanUtils can copy a single object to other.
Is it possible to copy an arraylist.
For example:
FromBean fromBean = new FromBean("fromBean", "fromBeanAProp", "fromBeanBProp");
ToBean toBean = new ToBean("toBean", "toBeanBProp", "toBeanCProp");
BeanUtils.copyProperties(toBean, fromBean);
How to achieve this?
List<FromBean > fromBeanList = new ArrayList<FromBean >();
List<ToBean > toBeanList = new ArrayList<ToBean >();
BeanUtils.copyProperties(toBeanList , fromBeanList );
Its not working for me. Can any one please help me.
Thanks in advance.
If you have two lists of equals size then you can do the following
for (int i = 0; i < fromBeanList.size(); i++) {
BeanUtils.copyProperties(toBeanList.get(i), fromBeanList.get(i));
}
If you have a list origin with data and list destination empty, the solution is:
List<Object> listOrigin (with data)
List<Object> listDestination= new ArrayList<Object>();
for (Object source: listOrigin ) {
Object target= new Object();
BeanUtils.copyProperties(source , target);
listDestination.add(target);
}
you can try something like this
for(int i=0; i<fromBeanList.size(); i++){
BeanUtils.copyProperties(toBeanList.get(i) , fromBeanList.get(i) );
}
Hope this helps..
Oops it is already explained by someone now..
anyways try it.
What you can do is to write your own generic copy class.
class CopyVector<S, T> {
private Class<T> targetType;
CopyVector(Class<T> targetType) {
this.targetType = targetType;
}
Vector<T> copy(Vector<S> src) {
Vector<T> target = new Vector<T>();
for ( S s : src ) {
T t = BeanUtils.instantiateClass(targetType);
BeanUtils.copyProperties(s, t);
target.add(t);
}
return target;
}
}
A step further would also be to make the List type generic - this assumes you want to copy Vectors.
BeanUtils.copyProperties, It only copy the property of same name. So, In case of ArrayList you can't do that.
According to docs:
Copy property values from the origin bean to the destination bean for
all cases where the property names are the same.
In spring BeanUtils.copyProperties, arguments are just opposite than apache commons lib
for(FromBean fromBean: fromBeanList) {
if(fromBean != null) {
ToBean toBean = new ToBean();
org.springframework.beans.BeanUtils.copyProperties(fromBean, toBean);
toBeanList.add(toBean);
}
}