Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

javabeans

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;    .................... 
like image 216
user2683519 Avatar asked Nov 04 '13 02:11

user2683519


People also ask

How do you copy properties of beans?

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.

How do I copy one bean to another in spring?

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

How do you copy an object in Java?

The clone() method of the class java. lang. Object accepts an object as a parameter, creates and returns a copy of it.


2 Answers

Use BeanUtils:

import org.apache.commons.beanutils.BeanUtils;  UserBean newObject = new UserBean();  BeanUtils.copyProperties(newObject, oldObject); 
like image 75
Mariusz Jamro Avatar answered Oct 04 '22 02:10

Mariusz Jamro


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.

like image 29
Jasper Blues Avatar answered Oct 04 '22 04:10

Jasper Blues