Reputation: 137
I have two classes, Employee
and Customer
, which have similar properties like name
, id
, et cetera. I want to populate objects 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> customers = new ArrayList<>();
empList.foreach(e -> {
Customer customer = new Customer();
customer.setCustomerName(e.getEmployeeName()); // Et cetera
customers.add(cutomer);
});
// What I am looking for
List<Customer> customers = Utils.getObject(empList, Customer.class);
Here are my POJOs
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 manually populating list from employee to customer and vice versa I want to use any third-party library like Apache Commons.
Upvotes: 6
Views: 31742
Reputation: 44414
Reflection is usually the worst way to accomplish something:
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 copying mutable 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?
Upvotes: 2
Reputation: 15908
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);
Upvotes: 11