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

1

7

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?

Sharolynsharon answered 1/9, 2016 at 6:33 Comment(3)
You can also use a Provider to instantiate your destination class.Irradiate
Hi Jonathan, yes that is what I ended up doing, see my own answer.Sharolynsharon
@Lars: I ran into the same problem as you but then tried out a private no-args ctor (even though the message says otherwise). ModelMapper is capable of reading a private ctor (v0.7.6) and as such you are still protected against unwanted instantiation/use of your class. In fact, by proactively placing a private no-args ctor you can (specifically through commenting) make your peers aware that you designed this class to not expose a no-args ctor.Tillis
S
8

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());
    });
Sharolynsharon answered 2/9, 2016 at 5:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.