From string to enum using mapstruct

m.zemlyanoi picture m.zemlyanoi · Feb 1, 2018 · Viewed 24.4k times · Source

I want to convert String to enum using mapstruct

enum TestEnum {
   NO("no");
   String code;

   TestEnum(String code) {
     this.code = code
   }

   public String getCode() {
    return code;
   }
}

I have a code that I've got from service and I want to convert this code to Enum how to do it with easier way by mapstruct

Answer

Bertrand Cedric picture Bertrand Cedric · Feb 5, 2018

Here is a solution with an abstract mapper, but if you want you can convert it with a default methode or a class

@Mapper
public abstract class TestMapper {

    abstract Source toSource(Target target);
    abstract Target totarget(Source source);

    String toString(TestEnum test){
        return test.getCode();
    }
    TestEnum toEnum(String code){
        for (TestEnum testEnum : TestEnum.values()) {
            if(testEnum.equals(code)){
                return testEnum;
            }
        }
        return null;
    }
}

public class Source {    
    String value;    
    public String getValue() {
        return value;
    }    
    public void setValue(String value) {
        this.value = value;
    }    
}

public class Target {
    TestEnum value;
    public TestEnum getValue() {
        return value;
    }
    public void setValue(TestEnum value) {
        this.value = value;
    }
}