function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Karan Khanna 6Karan Khanna 6 

Calling Batch class dynamically using custom Interface

Hi Team,

I had a business case to run Batch class concurrently, I was successfully able to accomplish that by writing another Batch class which creates chunks of data and call main Batch class n number of times. Now I am trying to make that concurrent class generic so that it can work with any sObject and be able to call any Batch class whose name I will be passing through custom setting.

I am using Type Class to implement this (https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_type.htm%23apex_methods_system_type)

I have used this in past and it works fine with Apex classes but in case of Batch class I am getting below error:
Compile Error: Argument must be an object that implements Database.Batchable at line 87 column 17
 
Type classType = Type.forName('MyBatchClassName');
MyInterFaceName obj = (MyInterFaceName)classType.newInstance();
obj.runBatchConcurrently(); // This is the method which I declared in Interface and implemented in Batch class               
system.debug('### obj'+obj); // In debug I am able to see instance of my Batch class
database.executeBatch(obj, 200); // Compile error is coming here

 
ForceMantis (Amit Jain)ForceMantis (Amit Jain)
It is giving compile time error becuase MyInterFaceName does not implement Database.Batchable method that are needed by Salesforce Batch Apex Execution engine call that you are doing by calling Database.executeBatch() method.

Fo resolve it you have to slightly refactor your code. MyInterFaceName has method runBatchConcurrently which is implemented in every batch class. So every implementation of runBatchConcurrently withing Batch class will create a instance of container Batch class and execute it via Database.executeBatch() method.

Hope this helps!
Karan Khanna 6Karan Khanna 6
Thanks Amit, it worked by typecasting the instance.
 
database.executeBatch((Database.Batchable<sObject>)obj, 200);

 
ForceMantis (Amit Jain)ForceMantis (Amit Jain)
That's great, for benefit of others if will be great if you choose best answer and mark the question as resolved.