6

I want to use Enum values in my Apex code as we have some strict types when working with an external service, however when I get a response from the external service I'm struggling to convert the String Representation of the Enum value back to the Enum so it can be used later in my code.

To do this in C# I'd do this:

DayOfWeek wednesday = 
      (DayOfWeek)Enum.Parse(typeof(DayOfWeek), "Wednesday");

but in Apex code I can't find a way to do this. Does anybody have a solution?

thegogz
  • 654
  • 6
  • 14

3 Answers3

9

This isn't generic, but it would work:

String dayOfWeekNameToMatch = 'Wednesday';
DayOfWeek dayOfWeekMatch;
for (DayOfWeek dow: DayOfWeek.values()) {
    if (dow.name() == dayOfWeekNameToMatch) {
        dayOfWeekMatch = dow;
        break;
    }
}
Daniel Blackhall
  • 632
  • 6
  • 14
barelyknown
  • 5,510
  • 3
  • 34
  • 46
  • I think I'm ok with it not being generic I don't have a huge amount of enums in my code I can write a utility method for each one. – thegogz Mar 23 '12 at 16:03
  • 2
    I've posted the Idea [Apex Enum parse from string](https://success.salesforce.com/ideaView?id=08730000000LfWhAAK) to see if this could be handled directly from Apex. – Daniel Ballinger Oct 16 '15 at 00:39
1

The "generic" way to do this for any enum:

public static Object parseEnum(string enumString, Type enumType) {
    Type cType = Type.forName(String.format('List<{0}>', new List<String>{ enumType.getName() }));
    return ((List<Object>) JSON.deserialize(String.format('["{0}"]', new List<String>{ enumString }), cType))[0];
}

Calling it is a bit awkward, but still better than other solutions (IMO):

TriggerOperation operationType = (TriggerOperation) 
     parseEnum('before_delete', TriggerOperation.class);
System.debug(operationType);  // -> BEFORE_DELETE

Gotta love apex :)

NSjonas
  • 10,693
  • 9
  • 66
  • 92
0

If you have several String values for cast to enum and wouldn't like to iterate over the enum each time, you can define special map with lazy initialization:

public static Map<String, DayOfWeek> dayOfWeekByNames {
    get {
        if (dayOfWeekByNames == null) {
            dayOfWeekByNames = new Map<String, DayOfWeek>();

            for (DayOfWeek dayOfWeek : DayOfWeek.values()) {
                dayOfWeekByNames.put(dayOfWeek.name(), dayOfWeek);
            }
        }
        return dayOfWeekByNames;
    }
    private set;
}

Next just use this map for casting:

DayOfWeek dayOfWeek = dayOfWeekByNames.get('Monday');
סטנלי גרונן
  • 2,917
  • 23
  • 46
  • 68