How to copy properties from a bean to another bean in different class?

user2683519 picture user2683519 · Nov 4, 2013 · Viewed 87.7k times · Source

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;
   ....................

Answer

Mariusz Jamro picture Mariusz Jamro · Nov 4, 2013

Use BeanUtils:

import org.apache.commons.beanutils.BeanUtils;

UserBean newObject = new UserBean(); 
BeanUtils.copyProperties(newObject, oldObject);