Converting/Parsing an Enumeration to a String More Generically code example
Example: Converting/Parsing an Enumeration to a String More Generically
private interface EnumerationToStringHelper
{
List<Object> ProvideEnumerationValues();
Boolean CompareEnumerationToString(String possibleEnumeration, Object enumerationValue);
}
private class ExampleEnumToStringHelper implements EnumerationToStringHelperExampleEnum
{
public List<Object> ProvideEnumerationValues(){ return (List<Object>)ExampleEnum.values(); }
public Boolean CompareEnumerationToString(String possibleEnumeration, Object enumerationValue)
{
return ((ExampleEnum)enumerationValue).name().equalsIgnoreCase(possibleEnumeration);
}
}
private static Map<Type, EnumerationToStringHelper> TypeToEnumerationMap;
private static void PopulateTypeToEnumerationMap()
{
TypeToEnumerationMap = new Map<Type, EnumerationToStringHelper>
{
Type.forName('ExampleEnum') => new ExampleEnumToStringHelper()
};
}
public static Object ConvertStringToEnumeration(Type enumerationType, String possibleEnumeration)
{
if(possibleEnumeration == null) return null;
if(TypeToEnumerationMap == null)
PopulateTypeToEnumerationMap();
EnumerationToStringHelper conversionAction = TypeToEnumerationMap.get(enumerationType);
if(conversionAction == null)
throw new EnumerationToStringException('The Type you enter is either a) not an enumeration or b) not a supported enumeration.');
for(Object particalarEnumValue : conversionAction.ProvideEnumerationValues())
if(conversionAction.CompareEnumerationToString(possibleEnumeration, particalarEnumValue))
return particalarEnumValue;
return null;
}
public class EnumerationToStringException extends Exception { }