1

I am trying to convert String to an enum value. but I am getting null pointer exception. Below is the code which I have tried to convert. (I have checked other stackoverflow questions before asking the question)

public static Object parseEnum(String enumString, Type enumType) {
    Type cType = Type.forName(
        String.format('List<{0}>', new List<String>{ enumType.getName() })
    );
    System.debug('cType ' + cType); // throws null pointer exception
    return ((List<Object>) JSON.deserialize(
        String.format('["{0}"]', new List<String>{ enumString }),
        cType
    ))[0];
}

public enum Markup_Category {
    Admin,
    DC,
    Frozen
}

this is my methods which I am using to convert from String to Enum type. I am calling below code in the anonymous window for testing.

String markupCategory = 'Admin';
Markup_Category enumBoniMarkupCategory = (Markup_Category) parseEnum(
            markupCategory,
            Markup_Category.class
);

It is throwing null pointer exception at System.debug();. If someone can help me what I am doing wrong or any other suggestions would be great.

PS: Please ignore any typo mistake as code is compelling correctly.

1
  • Im pretty sure the issue is coming from the JSON.deserialize() although Salesforce is reporting it on the System.debug(). If you remove the JSON.deserialize() , take a look at the output of your debug, I think you are getting a null Type. – TSmith Dec 15 '20 at 14:52
4

In testing this myself, I found that enumerations and classes declared inside of Anonymous Apex do not work with Type.forName() on any level. The following all return null:

  • Type.forName(String.format('List<{0}>', new List<Object>{MyEnum.class.getName()}));
  • Type.forName('List<MyEnum>');
  • Type.forName('MyEnum');

If you save that enum as a proper class, the parseEnum method you provided should work as you expect when testing it from anonymous apex (even if parseEnum is itself defined in the anonymous apex window) ...provided the enum itself is visible (i.e. not private and being called from outside the class that would have visibility of it)

3
  • I had thought this myself, although it would be nice if Salesforce threw the exception in the right code block! – TSmith Dec 15 '20 at 16:08
  • Thanks, @Derek for the reply but I have defined Enum in one of my class. I am only testing it through an anonymous window – Sagar Hinsu Dec 16 '20 at 9:22
  • @SagarHinsu Is that class saved as a proper apex class, or is the class defined in the anonymous window? If your enum is inside of a class, you need to add the outer class name as well (i.e. instead of using Markup_Category.class, you'd need to use MyOuterClass.Markup_Category.class) – Derek F Dec 16 '20 at 13:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.