Elye Elye - 1 month ago 4
Java Question

How to convert String to Enum, changing to capital before that?

I have an enum where

public enum Regular {
NONE,
HOURLY,
DAILY,
WEEKLY;

public String getName() {
return this.name().toLowerCase();
}
}


Where we could convert it to Lower case when we get it. But if I were to convert from String to Enum, I have to explicitly remember to set
toUpperCase()


Regular.valueOf(regular.toUpperCase());


Is there a way to define this in my Enum class, where it will auto convert all string to UpperCase to compare it?

Answer

No, there isn't a way to do it.

But, once you create another method String getName() to "override" the default implementation of name(). I thought that you have to do the same with Regular valueOf() ,i.e., create another method Regular valueOfByName().

public enum Regular {
    NONE,
    HOURLY,
    DAILY,
    WEEKLY;

    public String getName() {
        return this.name().toLowerCase();
    }

    public static Regular valueOfByName(String name){
        return valueOf(name.toUpperCase());
    }
}