如何使用mapstruct将枚举映射到布尔值?

问题描述:

我有一些自动生成的枚举,需要将它们映射到MapStruct映射器中的布尔值.他们是这样的:

I have some auto-generated enums that I need to map to boolean values in a MapStruct mapper. They go like this:

enum YN {
    Y("Y"), N("N")
}

enum ZO {
    _0("0"), _1("1")
}

我尝试使用@ValueMappings(),但是没有用:

I've tried to use @ValueMappings(), but it didn't work:

@ValueMappings({
    @ValueMapping(source="Y", target=true),
    @ValueMapping(source="N", target=false)
)
Boolean map(YN value);

如何实现此映射?

ValueMappings are used for mapping between two Enums. You can't use them to map an Enum to something else. For your defined mapping you will have to write a mapping by yourself. Then MapStruct can use that one in other mappers.

abstract class Mapper {
    Boolean map(YN value) {
        return YN.Y.equals(value);
    }

    Boolean map(ZO value) {
        return ZO.O.equals(value);
    }
}