From string to enum using mapstruct

m.zemlyanoi :

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

Bertrand Cedric :

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=476050&siteId=1