使用 Modelmapper,如何映射到没有 default/no-args 构造函数的 class?
Using Modelmapper, how do I map to a class with no default/no-args constructor?
我想映射到只有一个带 3 个参数的构造函数的源目标。我收到以下错误:
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.
当我在源目标中插入无参数构造函数时,它会起作用,但这可能会导致 class 的误用,所以我宁愿不这样做。
我试过使用转换器,但似乎不起作用:
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;
}
};
是否可以告诉 modelmapper 如何使用无参数构造函数映射到目的地?
这似乎可以解决问题:
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());
});
我想映射到只有一个带 3 个参数的构造函数的源目标。我收到以下错误:
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.
当我在源目标中插入无参数构造函数时,它会起作用,但这可能会导致 class 的误用,所以我宁愿不这样做。
我试过使用转换器,但似乎不起作用:
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;
}
};
是否可以告诉 modelmapper 如何使用无参数构造函数映射到目的地?
这似乎可以解决问题:
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());
});