Type.ForName is not working in apex

apextype

I have an implementation where i'm storing class name in custom metadata & trying to instantiate the class in apex using Type.forName but getting:

Method does not exist or incorrect signature: void forName(String)
from the type String

The line causing this issue is something like this

 list<customMetadata__mdt> result = [SELECT MasterLabel,Id,ClassName__c FROM customMetadata__mdt];

 Type classname=Type.forName(result[0].ClassName__c);

Best Answer

Standard Type is a part of the standard System namespace. Check it here

In order, to fix a problem, where you have a local variable with the same name, you can explicitly mention, that it is a class from a System namespace. In your example that should be.

List<customMetadata__mdt> result = [SELECT MasterLabel,Id,ClassName__c FROM customMetadata__mdt];

Type classname = System.Type.forName(result[0].ClassName__c);

Moreover, I recommend you to use a method forName that is accepting two parameters. First - namespace of where this Type is located. That would allow you to omit confusion, if this code will be running on a org with a namespace:

List<customMetadata__mdt> result = [SELECT MasterLabel,Id,ClassName__c FROM customMetadata__mdt];
    
Type classname = System.Type.forName(null, result[0].ClassName__c);