5

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
1
  • 1
    Can you show few initial lines of MyInterFaceName?
    – Ashwani
    Jul 25, 2016 at 18:55

2 Answers 2

5

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);
1
0

I think the problem is that your new "myInterfaceName" is competing with SFDC's "database.Batchable" for attention from the compiler. Consider using a concrete class that implements the database.batchable interlace, but also includes whatever methods you need. That class can instantiate your specific custom class by name and call it's methods using your interface. It would look a little like this:

public class myBatch implements Database.Batchable<sObject> {
     public MyInterfaceName myImplementation;
     public myBatch(string typeName) {
        Type classType = Type.forName(typeName);
        MyInterFaceName myImplementation = (MyInterFaceName)classType.newInstance();
     }
     public void execute(Database.BatchableContext BC, list<sObject> records){
     for(sobject r records) { 
          this.myImplementation.process(r);
     }
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .