+ Start a Discussion
Monin SavantMonin Savant 

Assign Type dynamically and passing it to a method

I want to create a class object knowing only its name. This object belongs to Batch, but I don't know which one. So i have to run it by name only. i get error when i pass sObject to executeBatch.
 
@AuraEnabled
    public static void run(String batchName){
        sObject newObject = (sObject)Type.forName(batchName).newInstance();
        Database.executeBatch(newObject);
    }
How to bypass it.
Thanks in advance.
Best Answer chosen by Monin Savant
GulshanRajGulshanRaj
Hi Monin,

The key is to use the right Type cast which is  Database.Batchable<sObject> 

You can use the code like this:
Type dynamicApexType = Type.forName('BatchClassName');
Database.Batchable<sObject> b = (Database.Batchable<sObject>) dynamicApexType.newInstance();
database.executebatch(b);


Thanks
Gulshan Raj (https://forceblazer.com/)