Apex Get Enum from String

Get Enum from String
  public Enum EventType { USER_LOGIN, USER_LOGOUT, USER_COMPLETE_FORM, USER_CLICK }

  static Map<String, EventType> nameToEvenType {
    get {
        Map<String, EventType> eventTypeValues = new Map<String, EventType>();
        if (nameToEvenType == null){
          for (EventType enumValue : EventType.values()){
              eventTypeValues.put(String.valueOf(enumValue).toUpperCase(), enumValue);
          }
        }
        return eventTypeValues;
    }
    private set;
}

public static EventType getEventType(String name){
    return String.isBlank(name) ? null : nameToEvenType.get(name.toUpperCase());
}

Test Class
@IsTest
public static void testNameToEvenType(){
 	Test.startTest();
      System.assertEquals(Events.EventType.USER_LOGIN, Events.getEventType('USER_LOGIN'));
      System.assertEquals(Events.EventType.USER_LOGOUT, Events.getEventType('USER_LOGOUT'));
      System.assertEquals(Events.EventType.USER_COMPLETE_FORM, Events.getEventType('USER_COMPLETE_FORM'));
      System.assertEquals(Events.EventType.USER_CLICK, Events.getEventType('USER_CLICK'));
    Test.stopTest(); 
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: