How do copy properties from one object to another in java

Viewed 8396

I am having two objects Employee and Customer having similar object properties like name, id etc I want to populate objects vice versa from List<Employee> empList to List<Customer> customerList and vice versa.

   List<Employee> empList=getEmployeeList();
   // Here is what i am trying so far
   List<Customer> cutomers=new ArrayList<Customer>();
   empList.foreach(e->{
     Customer customer = new Customer();
     customer.setCustomerName(e.getEmploueeName());//etc
     customers.add(cutomer);
   })
   // what i am looking for
   List<Customer> customers=Utils.getObject(empList,Customer.class);

Here is java POJO

class Employee {

 private String employeeName;

 private int age;

 private EmployeeDetails details;
 }

class EmployeeDetails {
  private String name;

  private int salary;
 }


class Customer{

 private String customerName;

 private int age;

 private CustomerDetails details;
}

class CustomerDetails {
 private String name;

 private int salary;
}

Instead of populating list from employee to customer and vice versa i want to use any 3rd part library like Apache Commons

2 Answers

You can use BeanUtils:

import org.apache.commons.beanutils.BeanUtils;

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

If looking for deep copy then Use SerializationUtils.clone method from the Apache Commons Lang. It copies the entire class hierarchy.

SerializationUtils.clone(object);

Reflection is usually the worst way to accomplish something:

  • Reflection cannot be checked at compile-time for errors.
  • Reflection is rarely optimized by the Java runtime.
  • Relying on identical property names is invisible to maintainers of either class.

Instead, you can create an additional constructor:

public Customer(Employee source) {
    setCustomerName(source.getEmployeeName());
    setAge(source.getAge());

    if (source.getDetails() != null) {
        setDetails(new CustomerDetails(source.getDetails()));
    }
}

And:

public CustomerDetails(EmployeeDetails source) {
    setName(source.getName());
    setSalary(source.getSalary());
}

That way, everything is checked for correctness when you compile. Also, you can be smart about mutable copying child objects.

Before you object to how much work it is to write the get- and set-calls by hand, consider that you only have to write the code once. It won’t really take that much time, will it?

Related