'How to map enum to String using Mapstruct

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


Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ben Zegveld