Convert string to enum in Apex

Posted on 07-03-2013 12:26 by graham
It often happens that you might want to convert a Apex string to an enum value that corresponds to it. Unfortunately, in Salesforce, there is no such method as SomeEnum.valueOf(String). In order to parse a string value to an enum, you have to iterate through all the enum values and pick the one whose name is identical to your input string:
Enum ViewType { DETAILS, GENERAL };

public ViewType convert (String val)
for (ViewType vt: ViewType.values())
if ( == val)
return vt;

return null;

If you want to convert enum to string, use our other tutorial about enum conversion.
it's unconscionable to me that this is not built in to Apex.
Added on 13-02-2014 06:32 by anonymous


Add comment

Has this tutorial been helpful to you? Or do you see anything wrong? We appreciate your opinion!
Your comment:
Show formatting hints
HTML is disallowed, but in your text you can use the following markup
  • [code][/code] for a block of code
  • [tt][/tt] for inline code
  • [link]link href|link anchor[/link] for links
  • [b][/b] for bold text
+ Ask a question
If you have a technical question related to programming and computers, ask it here. Other users will help you solve it!
Unanswered questions
Share your knowledge by helping others solve their problems