1

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.

1 Answer 1

1

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

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.