Как добраться до целевого объекта в методе AbstractConverter.convert () ModelMapper - PullRequest
0 голосов
/ 23 мая 2019

Я хотел бы отобразить поля из source в существующий объект dest через пользовательский конвертер. Не могли бы вы предложить канонический способ охватить dest объект из AbstractConverter#convert()

Пожалуйста, найдите код ниже:

Source source = new Source(xxx);
Dest dest = new Dest(yyy);

modelMapper.addConverter(new AbstractConverter<Source, Dest>() {
  @Override
  protected Dest convert(Source source) {
      // here I need to access 'dest' object in order to manually map fields from 'source'
  });

modelMapper.map(source, dest);

Ответы [ 2 ]

1 голос
/ 23 мая 2019

Если вы хотите получить доступ к целевому объекту, вы не должны использовать AbstractConverter, а анонимный конвертер:

modelMapper.addConverter(new Converter<Source, Dest>() {
    public Dest convert(MappingContext<Source, Dest> context) {
         Source s = context.getSource();
         Dest d = context.getDestination();
         d.setYyy(s.getXxx() + d.getYyy()); // example of using dest's existing field
         return d;
     }
});
0 голосов
/ 23 мая 2019

Переместить Dest dest = new Dest(yyy) в тело нового AbstractConvertor.

modelMapper.addConverter(new AbstractConverter<Source, Dest>() {

  private Dest dest = new Dest(yyy);

  @Override
  protected Dest convert(Source source) {
      // here I need to access 'dest' object in order to manually map fields from 'source'
  });
...