Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I parse a String and return an Enum value in Apex Code?

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?

like image 379
thegogz Avatar asked Mar 23 '12 11:03

thegogz


1 Answers

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;
    }
}
like image 80
barelyknown Avatar answered Sep 24 '22 17:09

barelyknown