user4695271
user4695271

Reputation:

Map enum to string value

I'm using a recent version of MapStruct. I'm trying to map the values of the corresponding string values to the actual enum value.

For instance, this is my 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. 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.

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.

Upvotes: 1

Views: 3493

Answers (1)

Filip
Filip

Reputation: 21403

MapStruct has the concept of @ValueMapping that can be used to map a String into an Enum.

e.g.

@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. However, an alternative approach would be to use a custom method to do the mapping:

e.g.

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");
    }

}

Upvotes: 1

Related Questions