2

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

1 Answer 1

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, 2020 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 Oct 21, 2020 at 10:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .