问题
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.
回答1:
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));
}
回答2:
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);
}
回答3:
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.
回答4:
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.
回答5:
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.
来源:https://stackoverflow.com/questions/19312055/beanutils-copyproperties-to-copy-arraylist