5

How can I convert String to enum value?

public enum Season {WINTER, SPRING, SUMMER, FALL}
Season season1;
String winterString = 'WINTER';

season1 = winterString; <-- This gives error of course, but is there a way to do it like in java?
3
  • Do you think a if else statement will help you? – Saumya Ranjan Satapathy May 12 '16 at 13:15
  • Are you trying to cast Winter to Season1, Spring to Season2, etc? – crmprogdev May 12 '16 at 13:15
  • @crmprogdev I have string parameter passed from visualforce, and I recieve string in apex method. So I need to change controller state depending and I would like to use enum to keep code clean. If this is not possible, I can change my code to work with strings instead of enum. – Vladyslav K May 12 '16 at 14:06
8

The String.valueOf method works great against Enum values, so you can build a map as follows:

Map<String, Season> seasonValues = new Map<String, Season>();
for (Season enumValue : Season.values())
{
    values.put(String.valueOf(enumValue).toUpperCase(), enumValue);
}

I would probably make it static. Something like:

static Map<String, Season> nameToSeason
{
    get
    {
        // lazy load pattern:
        if (nameToSeason == null)
        {
            //instantiation logic outlined above
        }
        return nameToSeason;
    }
    private set;
}
public static Season getSeason(String name)
{
    return String.isBlank(name) ? null : nameToSeason.get(name.toUpperCase());
}
2
  • my two cents - anything that is this much effort to implement is just wasting my time – Caspar Harmer Jun 26 '20 at 0:37
  • 1
    No doubt about it. – Adrian Larson Jun 26 '20 at 0:58
2

In the above, if using enums, what you omitted is something like this:

Season e = Season.WINTER;

Season m(Integer x, Season e) {

    if (e == Season.WINTER) return e;
     //...
} 

You need to pass an integer to equate 1 with WINTER.

Now you could take and create a map of type map<string,integer> or of type map<string,string> to get key/value pairs such as ('WINTER',1) or ('SEASON1','WINTER'). The former could be used to quickly convert your strings for use with your enum class while the latter could be used entirely on their own in place of the enums.

Since I don't know exactly what your use case is, I can't really guide you, but I suspect that a map of some kind might be a better solution for you.

2
  • 2
    Seasong? Sounds like an object for pirates. :) – Adrian Larson May 12 '16 at 15:43
  • 4
    Typos happen to us all, unless of course you're a pirate. :P – crmprogdev May 12 '16 at 16:02

Not the answer you're looking for? Browse other questions tagged or ask your own question.