36

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,040,783
  • 362
  • 3,548
  • 3,513
user2683519
  • 727
  • 5
  • 11
  • 17

4 Answers4

75

Use BeanUtils:

import org.apache.commons.beanutils.BeanUtils;

UserBean newObject = new UserBean(); 
BeanUtils.copyProperties(newObject, oldObject);
prashant thakre
  • 4,787
  • 2
  • 25
  • 38
Mariusz Jamro
  • 29,116
  • 24
  • 107
  • 151
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
  • 27,820
  • 20
  • 98
  • 179
  • 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,248
  • 1
  • 20
  • 25
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