35

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;
   ....................
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
user2683519
  • 747
  • 5
  • 11
  • 19

4 Answers4

78

Use BeanUtils:

import org.apache.commons.beanutils.BeanUtils;

UserBean newObject = new UserBean(); 
BeanUtils.copyProperties(newObject, oldObject);
prashant thakre
  • 5,061
  • 3
  • 26
  • 39
Mariusz Jamro
  • 30,615
  • 24
  • 120
  • 162
5

Check out the Dozer Framework - its an object to object mapping framework. The idea is that:

  • Usually it will map by convention.
  • You can override this convention with a mapping file.

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

Jasper Blues
  • 28,258
  • 22
  • 102
  • 185
  • Btw: I've voted to close this question as a duplicate, and expanded the existing Dozer answer here: http://stackoverflow.com/q/5937567/193634 – Jasper Blues Nov 04 '13 at 05:14
1

If you use Apache's library, BeanUtils, you can do this easily:

http://commons.apache.org/proper/commons-beanutils/

In particular, look at copyProperties(Object, Object)

http://commons.apache.org/proper/commons-beanutils/apidocs/org/apache/commons/beanutils/BeanUtils.html#copyProperties(java.lang.Object, java.lang.Object)

Copy property values from the origin bean to the destination bean for all cases where the property names are the same.

sdanzig
  • 4,510
  • 1
  • 23
  • 27
0

Use java reflection to set and get property values. There is spring bean property util which does the property value access. I would recommend to you java reflection.

Arvind
  • 199
  • 1
  • 5