How to use generics in modelmapper converter
Asked Answered
T

0

7

I am trying to use a Converter to specify the mapping of a simple String field in a DTO to a TypedString-Object which is part of another complex Object. The problem is, that TypedString is an Interface for several implementations. Such a converter works if I use a particular implementation, but not if I use generics to define the Type at runtime (see below). In this case, the converter is not selected at runtime when I called modelmapper.map().

This is not suitable for me due to I have to write converters for each implementation.

Is it possible to use generics to define the destination type at runtime?

P.S.: Current converter creates an instance via reflection, which works!

Thanks.

This code works

import org.modelmapper.Converter;
import org.modelmapper.ModelMapper;
import org.modelmapper.spi.MappingContext;

public class MyModelMapper extends ModelMapper {

  public MyModelMapper() {

    super();

    Converter<?, ?> converter = new Converter<String, ParticularDestType>() {

        @Override
        public SupplierId convert(MappingContext<String, ParticularDestType> context) {

            return (ParticularDestType) TypedStringConverter.createNewInstanceFromValue(context
                    .getSource(), ParticularDestType.class);
        }
    };

    addConverter(converter);
  }
}

@AllArgsConstructor
public class ParticularDestType implements TypedString {

  private String value;

}    

But this does not work if I add this to MyModelMapper (i.e. addConverter(new ModelMapperTypedStringConverter<ParticularDestType>()))!!!

import org.modelmapper.Converter;
import org.modelmapper.spi.MappingContext;

public class ModelMapperTypedStringConverter<T extends TypedString> implements Converter<String, T> {

  @Override
  public T convert(MappingContext<String, T> context) {

    return (T) TypedStringConverter.createNewInstanceFromValue(context.getSource(), context.getDestinationType());
  }
}    
Toady answered 22/11, 2016 at 23:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.