[SalesForce] Calling Batch class dynamically using custom Interface

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.

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

Best Answer

You must cast your instance to a Database.Batchable if you want to pass it to a Database.executeBatch call, even if you additionally implement a custom interface.

Type classType = Type.forName('MyBatchClassName');
MyInterfaceName instance = (MyInterfaceName)classType.newInstance();
// custom interface methods

Database.executeBatch((Database.Batchable<sObject>)instance, 100);