2
如何在ModelMapper中表达以下内容:要在目标中填充字段,我想要使用源的属性A(如果它非空),否则使用属性B.如何在ModelMapper中将源映射到同一对象
示例(以下代码,如果您不喜欢技术说明): 假设我想使用ModelMapper从源类SourceBigThing
到目标类Target
。 SourceBigThing
有两个属性,一个叫red
,另一个叫。这两个属性是不同类型的RedSmallThing
和GreenSmallThing
。这两件事都有一个名为name
的属性。 A SourceBigThing
可以有红色或绿色,但不能同时有两个(其他为空)。我想将Small Things的名称映射到目标类的属性。
例码:
class SourceBigThing {
private final SourceSmallThingGreen green;
private final SourceSmallThingRed red;
}
class SourceSmallThingGreen {
private final String name;
}
class SourceSmallThingRed {
private final String name;
}
class Target {
private TargetColorThing thing;
}
class TargetColorThing {
// This property should either be "green.name" or "red.name" depending
// on if red or green are !=null
private String name;
}
我试着玩的条件语句,但你不能有两个映射到相同的目标,因为ModelMapper抛出的副本映射异常:
when(Conditions.isNotNull()).map(source.getGreen()).setThing(null);
when(Conditions.isNotNull()).map(source.getRed()).setThing(null);
你可以在this gist找到一个失败的TestNG-Unit-Test。