Search code examples
javaspringdtoapache-commons-beanutils

Java - copy properties to another object


I have a few DTOs (from different APIs) that I need to convert. They have similar, but different fields.

Example:

class Volkswagen {
  String model;
  int year;
  String colour;
}

class BMW {
  String make;
  int manufactureYear;
  String colour;
}

What is the best way to convert these DTOs to my standard DTO?

I know there is BeanUtils, but there is not a direct way to map the fields. Currently, I am extracting one set of properties as VolkswagenMap, changing its keys using another V2BMap, and finally populating my standard DTO using a third BMWMap. As in,

extract()
   {"model": "Beetle", "year": 1990}
-> {"model": "make", "year": "manufacturedYear"}
-> {"make": "Beetle", "manufacturedYear": 1990}
populate()

Is there a more elegant way to do it? Thx in advance.


Solution

  • It's probably best to have a common interface for both. Then all of your service methods could act upon the interface instead of the concrete types.

    If you can change the sources of Volkswagen and BMW you could have both implement a common interface.

    If you can't change the sources of Volkswagen and BMW you could create adapters for each that implement a common interface.

    Eg

    public interface Car {
       int getYear();
       String getModel();
       String getColour();
    }
    
    public class CarAdapters {
       public static Car asCar(Volkswagen vw) {
          return new Car() {
             public int getYear() { return vw.year(); }
             public String getModel() { return vw.getModel(); }
             public String getColour() { return vw.getColour(); }
          };
       }
    
       public static Car asCar(BMW bmw) {
          return new Car() {
             public int getYear() { return bmw.getManufactureYear(); }
             public String getModel() { return bmw.getMake(); }
             public String getColour() { return bmw.getColour(); }
          };
       }
    }
    
    public class CarService {
       public Car paint(Car car, String colour) { ... }
       public void driveForward(Car car, long distance) { ... }
    }