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.
BeanUtils:- BeanUtils is a class of Apache commons library in java. it is used to copy, get and set the properties of one source object into another targeted object.
BeanUtils allows us to update the individual value in a map using a String-valued key. Here is the example code to modify the value in a mapped property: 5. Nested Property Access If a property value is an object and we need to access a property value inside that object – that would be accessing a nested property.
Therefore, it will not copy the property enrolledStudent in Course class because there is no property with the same name in CourseEntity class. 7. Conclusion In this quick article, we went over the utility classes provided by BeanUtils.
The last method is the clone () method that is a native ArrayList method. It copies the elements and returns a new List, similar to the previous solution. We create an ArrayList with elements and call the clone () method. At last, we cast the returned results to ArrayList<String> to get our desired result.
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);
}
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));
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With