问题描述
我一直在应用程序周围使用modelmapper和java 8 Optionals,因为它们是原始类型,所以工作正常;直到我将我的一个模型对象的字段更改为Optional类型。然后一切都崩溃了。结果很多图书馆都无法很好地处理泛型。
I've been using modelmapper and java 8 Optionals all around the application which was working fine because they were primitive types; until I changed one of my model objects' field to Optional type. Then all hell broke loose. Turns out many libraries cannot handle generics very well.
这是结构
public class MyObjectDto
{
private Optional<MySubObjectDto> mySubObject;
}
public MyObject
{
privae Optional<MySubjObject> mySubObject;
}
当我尝试映射 MyObjectDto $ c时$ c>到
MyObject
,modelmapper调用
When I attempt to map MyObjectDto
to MyObject
, modelmapper calls
public void setMySubObject(Optional<MySubObject> mySubObject){
this.mySubObject = mySubObject;
}
带可选< MySubObjectDto>
,我不明白这是怎么回事(他们之间没有继承)。当然崩溃很快。现在我已经改变我的二传手接受Dto类型只是为了生存一天,但从长远来看这不会起作用。有没有更好的解决方法,或者我应该创建一个问题?
with Optional<MySubObjectDto>
, which I don't understand how that's even possible (there is no inheritance between them). Of course that crashes fast. For now I've changed my setters to accept Dto type just to survive the day but that's not going to work on the long run. Is there a better way to get around this, or shall I create an issue?
推荐答案
所以我深入研究了模型映射代码看看一些通用实现:
So I digged into the modelmapper code and have done this looking at some generic implementations:
modelMapper.createTypeMap(Optional.class, Optional.class).setConverter(new OptionalConverter());
public class OptionalConverter implements ConditionalConverter<Optional, Optional> {
public MatchResult match(Class<?> sourceType, Class<?> destinationType) {
if (Optional.class.isAssignableFrom(destinationType)) {
return MatchResult.FULL;
} else {
return MatchResult.NONE;
}
}
private Class<?> getElementType(MappingContext<Optional, Optional> context) {
Mapping mapping = context.getMapping();
if (mapping instanceof PropertyMapping) {
PropertyInfo destInfo = ((PropertyMapping) mapping).getLastDestinationProperty();
Class<?> elementType = TypeResolver.resolveArgument(destInfo.getGenericType(),
destInfo.getInitialType());
return elementType == TypeResolver.Unknown.class ? Object.class : elementType;
} else if (context.getGenericDestinationType() instanceof ParameterizedType) {
return Types.rawTypeFor(((ParameterizedType) context.getGenericDestinationType()).getActualTypeArguments()[0]);
}
return Object.class;
}
public Optional<?> convert(MappingContext<Optional, Optional> context) {
Class<?> optionalType = getElementType(context);
Optional source = context.getSource();
Object dest = null;
if (source != null && source.isPresent()) {
MappingContext<?, ?> optionalContext = context.create(source.get(), optionalType);
dest = context.getMappingEngine().map(optionalContext);
}
return Optional.ofNullable(dest);
}
}
这篇关于ModelMapper处理java 8可选< MyObjectDto>字段为Optional< MyObject>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!