I have two java class with same properties names.How Can I copy all the properties to another bean filled with data.I don't want to use the traditional form to copy properties because I have a lot of properties.
Thanks in advance.
1 class
@ManagedBean @SessionScoped public class UserManagedBean implements Serializable { private static final long serialVersionUID = 1L; private String userSessionId; private String userId; private String name; private String adress; ......................
2 class
public class UserBean { private String userSessionId; private String userId; private String name; ....................
Copy Bean Properties Copying properties of one object to another object is often tedious and error-prone for developers. BeanUtils class provides a copyProperties method that copies the properties of source object to target object where the property name is same in both objects.
Using copyProperties(Object source, Object target, Class<?> editable) This method copies the property values of the given source bean into the given target bean, only setting properties defined in the given "editable" class (or interface).
The clone() method of the class java. lang. Object accepts an object as a parameter, creates and returns a copy of it.
Use BeanUtils
:
import org.apache.commons.beanutils.BeanUtils; UserBean newObject = new UserBean(); BeanUtils.copyProperties(newObject, oldObject);
Check out the Dozer Framework - its an object to object mapping framework. The idea is that:
. . therefore mapping files are as compact as possible. Its useful for many cases, such as mapping a use-case specify service payload on to the reusable core model objects.
When delivering the SpringSource training courses we used to point out this framework very often.
Edit:
These days try MapStruct.
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