Dynamic Calling of Static APEX Methods in Salesforce

APEX is a Salesforce server-side programming language allowing developers to implement complex business logic, manipulate data, and interact with external REST APIs.

APEX is a strongly typed language with Java-like classes and runtime, and its deployment is similar to source code compilation, meaning that an erroneous class cannot be deployed.

In essence, APEX code is static — what is compiled and deployed is what runs. However, there are occasions when it’s necessary to call APEX code dynamically at runtime.

For example, Nextian uses dynamic code tasks to support automation, integration and orchestration of workflow tasks. Users can write their own classes, deploy them to their org and use in Nextian workflows by passing class and method names as configuration parameters, all without modifying the Nextian core package.

The required functionality, written in pseudo-code, looks as follows:

final String className ='MyHelperClass';
final String methodName = 'myHelperMethod';

Object result = call(className, methodName, args);
 
ImportantThe method signature (arguments and returned value) must be known to the caller up front.
 

Salesforce provides a Callable interface to support dynamic calling of methods; however, it does not work for static methods.

This post demonstrates how to modify the Callable pattern to support static methods.

Modifying Callable Pattern for Static Methods

let’s assume that two custom objects are available in Salesforce:

  • Project__c — representing a project
  • Task__c — tasks underneath the project

The goal is to enable tasks to invoke a static method, assuming the task object id is passed as an argument and no return value is expected.

This can be achieved by modifying the standard Callable pattern as follows:

/**
* Example helper class, this class must be deployed on the org (rather than declared via anonymous APEX),
* otherwise 'static can only be used on methods of a top level type' compilation error will occur.
*/
public class HelperClass implements Callable {
    
    /**
     * Dynamically called static method.
     */
    public static void completeTask(Work_Order_Task__c t) {
        System.debug('Completing task ' + t.Id);
    }

    ... other methods ...

    /**
     * Callable::call() implementation, calling static function (completeTask, rather than this.completeTask)
     */
    public Object call(String action, Map<String, Object> args) {
        switch on action {
            when 'completeTask' {
                // It is best to keep the naming consistent with the original method signature, error checking is
                // omitted:
                completeTask((Work_Order_Task__c)args.get('t'));
                // call() expects an object to be returned, null is returned for void function, other types can be used as needed:
                return null;
            }

            ... handle other methods ...
            when else {
                // A standard Salesforce exception is used for simplicity:
                throw new CalloutException('Method not implemented');
            }
        }
    }    
}
 

The calling code would look as follows:

// Data for the dynamic call:
final String className = 'HelperClass';
final String methodName = 'completeTask';
Work_Order_Task__c t = [SELECT Id, Name FROM Work_Order_Task__c LIMIT 1];

// Obtain callable interface (this instantiates the class, but since the class has only one-non static member there's no overhead):
Callable c = (Callable) Type.forName(className).newInstance();

Object o = c.call(
        methodName,               // objects
        new Map<String, Object> { // argument map
                't' => t
        });
 

Conclusions

Dynamic APEX allows for the creation of highly flexible applications with configuration-driven runtime behavior using Callable interface.

Although Dynamic APEX does not natively support static methods, it can be extended to handle them by leveraging helper classes, as demonstrated above.

This modified pattern allows for advanced integration, automation, and other use cases managed solely through configuration, eliminating the need to modify existing APEX code.

Contact us today to find out how we can help you!

    Thank you for contacting Nextian. Your request was successfully submitted, we will get back to you within two working days.

    BY INDUSTRY

    Cloud Infrastructure Providers

    Cloud Software Companies

    Managed Service Providers

    Communications Service Providers

    BY ROLE

    CEO / Owner

    CRO / VP Sales

    CFO / VP Finance

    COO / VP Operations

    CPO / VP Product

    CIO / VP IT

    Product Management

    Plan, launch and manage your product offerings throughout their entire lifecycle.

    CPQ & Sales

    Quickly create accurate quotes for complex products, subscriptions and add-ons

    Order Management

    Ensure faster, consistent order delivery with tasks, workflows and automation

    Service Management, Support & Monitoring

    Retain and upsell customers with comprehensive account intelligence, support, monitoring, analytics

    Customer Portal

    Empower your customers with 24/7 self-service, support and on-line ordering

    NEXTIAN PLATFORM

    Platform Overview

    Billing Integration

    Network Monitoring Integration

    Reporting & Analytics