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?
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It only takes a minute to sign up.
Sign up to join this communityThe 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());
}
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.
Winter
toSeason1
,Spring
toSeason2
, etc? – crmprogdev May 12 '16 at 13:15