Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Empty String for Enum Value in Java

Tags:

java

enums

I have an object in Java which I am trying to set from an enum class with following structure.

public enum Code {
    CODE_A,
    CODE_B,
    CODE_C,
    CODE_D,
    CODE_E,
    CODE_F,
    EMPTY("")
}

Want to set my object to empty sting value. i.e. Object.setCode(Code.EMPTY)

And when I look at my Object, it should have "" instead of EMPTY as value for the property code.

Can someone suggest what's a workaround I can use ? I don't want to modify the Object.setCode setter which is as below:

public void setCode(Code code) {
    this.code = code;
}

Also the problem is Object.setCode(MustBe of Object-Code Type only)

like image 910
CodeMonkey Avatar asked Mar 10 '23 20:03

CodeMonkey


1 Answers

You can simply assign a value to each enum and override the toString() method so that calling Code.EMPTY returns the value "" instead of "EMPTY"

enum Code{

    CODE_A("STRING_A"),
    CODE_B("STRING_B"),
    EMPTY("");

    // Assigning a value to each enum
    private final String code;
    Code(String code){
        this.code = code;
    }

    // Overriding toString() method to return "" instead of "EMPTY"
    @Override
    public String toString(){
        return this.code;
    }

}

So running Code.CODE_A will return "STRING_A"
and running Code.EMPTY will return ""

like image 106
akgren_soar Avatar answered Mar 21 '23 07:03

akgren_soar