当字符串既不匹配枚举值也不匹配名称时,字符串值到枚举映射
String value to enum mapping when string neither matches enum value nor name
我正在尝试从字符串值映射到不直接匹配该字符串值的枚举(即字符串值是 "I",我想将其映射到枚举值 Industry.CREATOR ) 我在 mapstruct 中没有看到任何东西可以做这样的事情。
我希望它生成如下内容
switch (entityInd) {
case "I":
return Industry.CREATOR;
case "E":
return Industry.CONSUMER;
default:
return null;
}
使用代码字段丰富 Industry 枚举并添加迭代枚举值的静态方法和returns具有给定代码的枚举值
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
我正在尝试从字符串值映射到不直接匹配该字符串值的枚举(即字符串值是 "I",我想将其映射到枚举值 Industry.CREATOR ) 我在 mapstruct 中没有看到任何东西可以做这样的事情。
我希望它生成如下内容
switch (entityInd) {
case "I":
return Industry.CREATOR;
case "E":
return Industry.CONSUMER;
default:
return null;
}
使用代码字段丰富 Industry 枚举并添加迭代枚举值的静态方法和returns具有给定代码的枚举值
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