Search code examples
modelmapper

Using Modelmapper, how do I map to a class with no default/no-args constructor?


I want to map to a source destination which only have a constructor that takes 3 parameters. I get the following error:

Failed to instantiate instance of destination com.novasol.bookingflow.api.entities.order.Rate. Ensure that com.novasol.bookingflow.api.entities.order.Rate has a non-private no-argument constructor.

It works when I insert a no-args constructor in the source destination, but that can lead to misuse of the class, so I would rather not o that.

I have tried using a Converter, but that does not seem to work:

Converter<RateDTO, Rate> rateConverter = new AbstractConverter<RateDTO, Rate>() {
    protected Rate convert(RateDTO source) {
        CurrencyAndAmount price = new CurrencyAndAmount(source.getPrice().getCurrencyCode(), source.getPrice().getAmount());
        Rate rate = new Rate(price, source.getPaymentDate(), source.getPaymentId());
        return rate;
    }
};

Is it possible to tell modelmapper how to map to a destination with a no no-args constructor?


Solution

  • This seemed to do the trick:

        TypeMap<RateDTO, Rate> rateDTORateTypeMap = modelMapper.getTypeMap(RateDTO.class, Rate.class);
        if(rateDTORateTypeMap == null) {
            rateDTORateTypeMap = modelMapper.createTypeMap(RateDTO.class, Rate.class);
        }
        rateDTORateTypeMap.setProvider(request -> {
            RateDTO source = RateDTO.class.cast(request.getSource());
            CurrencyAndAmount price = new CurrencyAndAmount(source.getPrice().getCurrencyCode(), source.getPrice().getAmount());
            return new Rate(price, source.getPaymentDate(), source.getPaymentId());
        });