如何配置 MapStruct 在枚举值无法映射时抛出异常

Uro*_*s K 5 java enums mapstruct

这是我的映射器:

@Mapper
public interface ProductMapper {
    ProductClassification toProductClassification(ProductTypes pisType);
}
Run Code Online (Sandbox Code Playgroud)

其中ProductTypesProductClassification是枚举。我希望它在无法映射枚举时抛出异常,但出现编译器错误: The following constants from the source enum have no corresponding constant in the target enum and must be be mapped via adding additional mappings: EXTERNAL, UNKNOWN.

我尝试使用@ValueMappings注释,但只能将其配置为将值设置为 null,这是不够的:

@ValueMappings({
    @ValueMapping(source = MappingConstants.ANY_REMAINING, target = MappingConstants.NULL)
})
Run Code Online (Sandbox Code Playgroud)

将 MapStruct 映射器配置为在无法映射枚举常量时抛出异常的正确方法是什么?

Fil*_*lip 6

这可以使用MappingConstants.THROW_EXCEPTION并将其设置为ValueMapping#target.

因此,在此示例中,为了对任何剩余映射抛出异常,您可以编写:

@ValueMapping(source = MappingConstants.ANY_REMAINING, target = MappingConstants.THROW_EXCEPTION)
Run Code Online (Sandbox Code Playgroud)

请注意,此功能从版本 1.5 开始可用