I'm trying to map long type to Instant automatically using Converter.
Firstly I thought it's because it's primitive, but I tried to map Long and it doesn't work either.
What is interesting, Converter for String works perfectly.
What I'm interested in is in mapping long primitive type - I cannot change it to something else since it's Protobuf's generated code.
I tried to debug to find how converters are getting selected but I didn't succeed.
Please see this snippet:
import org.modelmapper.Conditions;
import org.modelmapper.Converter;
import org.modelmapper.ModelMapper;
import org.modelmapper.convention.MatchingStrategies;
import java.time.Instant;
import static junit.framework.TestCase.assertEquals;
public class Test {
public static class ProtobufMessage {
public long value1 = 123;
public Long value2 = 123L;
public String value3 = "123";
}
public static class Dto {
public Instant value1;
public Instant value2;
public Instant value3;
}
@org.junit.Test
public void test() {
final ModelMapper modelMapper = createModelMapper();
final Dto expected = new Dto();
expected.value1 = Instant.ofEpochMilli(123);
expected.value2 = Instant.ofEpochMilli(123);
final Dto actual = modelMapper.map(new ProtobufMessage(), Dto.class);
assertEquals(expected.value1, actual.value1);
assertEquals(expected.value2, actual.value2);
assertEquals(expected.value3, actual.value3);
}
private ModelMapper createModelMapper() {
final ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration().setImplicitMappingEnabled(true);
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
modelMapper.getConfiguration().setPropertyCondition(Conditions.isNotNull());
modelMapper.addConverter((Converter<Long, Instant>) context -> Instant.ofEpochMilli(context.getSource()));
modelMapper.addConverter((Converter<String, Instant>) context -> Instant.ofEpochMilli(Integer.parseInt(context.getSource())));
return modelMapper;
}
}
Any ideas of how to map long using Converter?
Thanks in advance