TransWikia.com

Attempt to de-reference a null object when using alternative to getGlobalDescribe

Salesforce Asked by Vneq on December 26, 2020

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

One Answer

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();
}

Correct answer by TSmith on December 26, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP