10

I can find answers where we have String to Enum mapping but I can't find how can I map an Enum to a String.

public class Result {
  Value enumValue;
}

public enum Value {
   TEST,
   NO TEST
}


public class Person {
  String value;
}

How can I map this ?

I tried :

@Mapping(target = "value", source = "enumValue", qualifiedByName = "mapValue")


 @Named("mapValue")
    default Person mapValue(final Value en) {
        return Person.builder().value(en.name()).build();
    }

2 Answers 2

5

mapstruct should support this out of the box. So @Mapping(target = "value", source = "enumValue") should suffice.

Complete example including target/source classes:


@Mapper
public interface EnumMapper {
    @Mapping( target = "value", source = "enumValue" )
    Person map(Result source);
}

class Result {
    private Value enumValue;

    public Value getEnumValue() {
        return enumValue;
    }

    public void setEnumValue(Value enumValue) {
        this.enumValue = enumValue;
    }
}

enum Value {
    TEST, NO_TEST
}

class Person {
    private String value;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}

This results in the following generated code:

@Generated(
    value = "org.mapstruct.ap.MappingProcessor",
    date = "2022-02-20T12:33:00+0100",
    comments = "version: 1.5.0.Beta2, compiler: Eclipse JDT (IDE) 1.4.50.v20210914-1429, environment: Java 17.0.1 (Azul Systems, Inc.)"
)
public class EnumMapperImpl implements EnumMapper {

    @Override
    public Person map(Result source) {
        if ( source == null ) {
            return null;
        }

        Person person = new Person();

        if ( source.getEnumValue() != null ) {
            person.setValue( source.getEnumValue().name() );
        }

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

1 Comment

Thank you Ben Zegveld, this solved all my Enum related problems.
4

I faced with the same issue.
But this doesn't work if your Enum isn't nested/inner class or if you need more complex logic. After generation with Mapstruct your import is invalid, so i fixed it with another approach.

  1. Create the default method with getting required data:
    default String getEnumValue(Result source) {
     return source.getEnumValue().name();
    }
  1. Call this method in your mapping:
    @Mapping( target = "value", expression = "java(getEnumValue(source))")
    Person map(Result source);

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.