当字符串既不匹配枚举值也不匹配名称时,字符串值到枚举映射

问题描述 投票:-2回答:1

我正在尝试从String值映射到直接与该字符串值不匹配的枚举(即字符串值为“I”,我想将其映射到枚举值Industry.CREATOR)我在mapstruct中没有看到任何内容做这样的事情。

我想它会产生如下的东西

switch (entityInd) {
            case "I":
                return Industry.CREATOR;
            case "E":
                return Industry.CONSUMER;
            default:
                return null;
        }
java mapstruct
1个回答
2
投票

让行业枚举丰富了代码字段并添加一个静态方法,它迭代枚举值并返回具有给定代码的枚举值

enum Industry {

    CREATOR("I")/*, here comes more values of the enum*/;

    private String code;

    Industry(String code) {
        this.code = code;
    }

    public static Industry forCode(String code) {

        return Arrays.stream(Industry.values())
                     .filter(industry -> industry.code.equals(code))
                     .findAny()
                     .orElse(null);
    }
}

对于用法,应定义Mapper,并在映射器中调用'Industry#forCode`方法

Industry industry = Industry.forCode("I");

Quick Guide to MapStruct文章的第6节详述了如何使用Mapper

© www.soinside.com 2019 - 2024. All rights reserved.