ModelMapper: mapping abstract classes during runtime
I also had this problem and solved this with:
public void configure(ModelMapper modelMapper) {
modelMapper.typeMap(QuestionDto.class, AbstractItem.class)
.setConverter(converterWithDestinationSupplier(Question::new));
modelMapper.typeMap(CriteriaDto.class, AbstractItem.class)
.setConverter(converterWithDestinationSupplier(Criteria::new));
}
private <S, D> Converter<S, D> converterWithDestinationSupplier(Supplier<? extends D> supplier ) {
return ctx -> ctx.getMappingEngine().map(ctx.create(ctx.getSource(), supplier.get()));
}
Converter uses supplier to create required instance and then uses right typeMap (QuestionDto -> Question or CriteriaDto -> Criteria) to map all properties.