Answers for "Converting/Parsing an Enumeration to a String More Generically"

0

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 { }
Posted by: Guest on September-23-2020

Code answers related to "Converting/Parsing an Enumeration to a String More Generically"

Browse Popular Code Answers by Language