1

In the following code

String myString = 'Account'; 
SObjectType sObjType = ((SObject) Type.forName(myString).newInstance()).getSObjectType();

When myString = a object name does not exist i get a NullPointerException: Attempt to de-reference a null object.

Is there any way to check this before getting this error without using Schema.getGlobalDescribe() ?

speed comparison between above and getXXDescribe methods

3

The problem is an invalid (or null) return on the Type class using forName.

You need to validate the return of forName before looking to cast into an SObjectType

String myString = 'InvalidClass'; 
Type classType = Type.forName(myString);

SObjectType sObjType;

if (classType != null) {
    sObjType = ((SObject) classType.newInstance()).getSObjectType();
}
2
  • i see, thank you ! – Vneq Oct 21 '20 at 9:08
  • 2
    it is also recommended to use Type.forName(null, className) to make sure, that code will work properly on namespaced orgs. First Param is the name of the namespace – Oleksandr Berehovskyi Oct 21 '20 at 10:46

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.