Many companies develop managed packages that expose Apex integration hooks. Often the initial approach requires:

  • a global interface (for the API to call)
  • an extension package (for the first integration)
  • custom metadata (to tell the base package about the existence of the extension...)

Unfortunately, the unavoidable Salesforce package dependency means the different parts are permanently coupled together, which complicates distribution and maintenance. So, how can we connect many products on Salesforce without a package dependency? Check this out:

Type reflector = Type.forName('CustomTaxService');
String inputs = '{"arg1":true,"arg2":2}';
Object impl = Json.deserialize(inputs, reflector);
String output = String.valueOf(impl); //calls toString

What just happened from the caller's point of view?

  1. we referenced a piece of Apex code
  2. provided multiple input arguments
  3. invoked any custom logic via Object.toString()
  4. received a return value that could be any type or types.

This method supports dependency-free calls between any number of managed packages, even different vendors. Every Apex object has toString() and it can be called outside the namespace!

  • We successfully avoid any custom interfaces.
  • There is no compiled dependency to the invoked code.

Here's what the callee class looks like:

public class CustomTaxService
{
    Boolean arg1;
    Integer arg2;

    override public String toString()
    {
        // do logic or callouts here
        List<Object> outputs = new List<Object>();
        
        // return calculated outputs here
        return Json.serialize(outputs);
    }
    
}

We are thrilled to see this tip used everywhere from shortcode parsers to product plugins.

Update: the platform finally offers a native mechanism!
You can use it as of the Winter '19 release - System.Callable interface in Apex