Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

modelmapper

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?

like image 293
Lars Rosenqvist Avatar asked Sep 01 '16 06:09

Lars Rosenqvist


1 Answers

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());
    });
like image 175
Lars Rosenqvist Avatar answered Oct 13 '22 20:10

Lars Rosenqvist