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

Instantiate and execute an Apex Class at runtime knowing just its NAME (string variable)???

Scenario - We are trying to setup a framework for Scheduler and BatchApex classes, whereby it will be possible to define (inside a custom object or custom setting) - list of Apex Class names (batch apex classes) and the order in which they should be executed.


These custom settings can be modified by Administrator so BatchApex3.class may need to be run first and BatchApex1.class after it. So we are defining BatchApex class names declaratively inside a custom setting.


Query - The real question here is, like what we do in Java using System.getRunTime().exec(STRING) to instantiate and run any Java class file at runtime, can we achieve similar with Apex ( realm??


or if you think we can achieve the requirement stated above using other means, do share your thoughts or suggestions.




- Best



As far as I know this it isn't possible to instantiate an apex class unless you know it's name at compile time. What you're after requires it to not be known until runtime, which is beyond the capabilities of apex at the moment.


Thanks for posting your thoughts.


These Apex classes are already created and we know their name in advance.


The Administrator would enter the name of Batch Apex class into a Custom Setting. So if I have defined 4 Batch Apex classes namely - processChildAccounts, processAllContacts, processOpportunities, processOppLineItems.


All that we want to do is enter "Names" of these classes into a Custom Setting.


Now an Apex Scheduler program gets invoked at midnight local time, queries Custom setting, find "processChildAccounts" as Step 1, and need to invoke a BatchApex class in system with same name.


So Scheduled Apex class should be able to instantiate this class and perform Database.executeBatch(instance of processChildAccounts).


Is this what you meant by knowing Apex class name after compilation???


Hope I am able to clarify the requirement elaborately.




Why is this difficult?  Why can't your write your Apex Scheduler class to query the custom setting, retrieve the "processChildAccounts" string and call a function called "dispatcher(String s)".


You write dispatcher as:


if (s == 'processChildAccounts") processChildAccounts();


if(s == 'BananaPickles") doBananaPickles();


and so on.  processChildAccounts can then go and do the Database.executeBatch(), etc.



e.g. you don't have to do the bind dynamically if you have a fixed, limited set of options that you can code into a decision tree.  And, it sounds like that's just what you have.   If you have multiple steps, join them as comma separated strings, and then your scheduler can burst them apart and call them one by one, etc.


Unless I'm missing something... best, Steve.