我有一些需要转换的 DTO(来自不同的 API)。他们有相似但不同的领域。
示例:
class Volkswagen {
String model;
int year;
String colour;
}
class BMW {
String make;
int manufactureYear;
String colour;
}
将这些 DTO 转换为我的标准 DTO 的最佳方法是什么?
我知道有
BeanUtils
,但没有直接的方法来映射字段。目前,我正在提取一组属性作为 VolkswagenMap
,使用另一个 V2BMap
更改其键,最后使用第三个 BMWMap
填充我的标准 DTO。如,
extract()
{"model": "Beetle", "year": 1990}
-> {"model": "make", "year": "manufacturedYear"}
-> {"make": "Beetle", "manufacturedYear": 1990}
populate()
有更优雅的方法吗?提前谢谢。
您可以都实现一个通用接口(或者为每个实现通用接口的适配器提供一个适配器),然后您的所有服务方法都可以在通用接口而不是具体类型上运行
例如
public interface Car {
int getYear();
String getModel();
String getColour();
}
public class CarAdapters {
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 static Car asCar(Volkswagen vw) {
return new Car() { ... };
}
}