给出以下类,接口Fruit
,示例实现和类FruitBasket
,该类包含Fruit
对象的实例:
private interface Fruit {
}
private static class Apple implements Fruit {
private String type;
// ommitted
}
private static class FruitBasket {
private Collection<Fruit> fruits = new ArrayList<>();
// ommitted
}
现在,对于实体类(省略所有注释),定义了以下类:
private static class FruitEntity {
}
private static class AppleEntity extends FruitEntity {
private String type;
// ommitted
}
private static class FruitBasketEntity {
private Collection<FruitEntity> fruits = new ArrayList<>();
// ommitted
}
现在,如果您执行
ModelMapper mapper = new ModelMapper();
FruitBasket basket = new FruitBasket();
basket.fruits.add(new Apple());
FruitBasketEntity entity = mapper.map(basket, FruitBasketEntity.class);
entity
确实具有类型FruitEntity
的对象,但是如何配置映射器以使用正确的实现类型进行转换?
另外,相反的映射也不起作用,因为Fruit
是一个接口并且没有公共构造函数。
FruitBasketEntity basketEntity = new FruitBasketEntity();
basketEntity.fruits.add(new FruitEntity());
// does not work
FruitBasket basket = mapper.map(basketEntity, FruitBasket.class);
源代码为here。