简体   繁体   English

将枚举映射到字符串值

[英]Map enum to string value

I'm using a recent version of MapStruct .我正在使用最新版本的MapStruct I'm trying to map the values of the corresponding string values to the actual enum value.我正在尝试将相应字符串值的值映射到实际的enum值。

For instance, this is my enum :例如,这是我的enum

@Getter
@RequiredArgsConstructor
@Accessors(fluent = true)
public enum Type {
  T1("SomeValue"),
  T2("AnotherValue");

  private final String label;
}

I have a Java type ( ForeignType ) with a field/member that receives the data (one of the string values in the enum ): SomeValue or AnotherValue .我有一个Java类型( ForeignType ),其字段/成员接收数据( enum中的字符串值之一): SomeValueAnotherValue Then I have a "controlled" type ( MyType ) and I would like to use in this one the actual enumeration constant ( T1 or T2 ), based on string value sent.然后我有一个“受控”类型( MyType ),我想在这个类型中使用实际的枚举常量( T1T2 ),基于发送的字符串值。

I'm looking for a way to use MapStruct to do this, because the application currently uses it for all mapping purposes, but so far I can't find a way to achieve this.我正在寻找一种使用MapStruct来执行此操作的方法,因为该应用程序当前将它用于所有映射目的,但到目前为止我找不到实现此目的的方法。

MapStruct has the concept of @ValueMapping that can be used to map a String into an Enum . MapStruct 具有@ValueMapping的概念,可用于将 String 映射到Enum

eg例如

@Mapper
public interface TypeMapper {


    @ValueMapping(target = "T1", source = "SomeValue")
    @ValueMapping(target = "T2", source = "AnotherValue")
    Type map(String type);


}

Doing the above MapStruct will implement a method for you.执行上述 MapStruct 将为您实现一个方法。 However, an alternative approach would be to use a custom method to do the mapping:但是,另一种方法是使用自定义方法进行映射:

eg例如

public interface TypeMapper {

    default Type map(String type) {
        if (type == null) {
            return null;
        }

        for(Type t: Type.values()) {
            if (type.equals(t.label()) {
                return t;
            }
        }

        throw new IllegalArgumentException("Cannot map label " + type + " to type");
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM