Call Apex class method on the fly (dynamically)

1.9K    Asked by Ankesh Kumar in Salesforce , Asked on Jul 19, 2021

Is there any way I can call the apex method from class if both class name and method are stored in the string.

String strClass = 'BatchUtil'; String strMethod = 'updateAccounts'

now I want to call the above method.. is it possible? I was doing research and came across the following - (not sure how this works and how to call it from salesforce) ExecuteAnonymousResult[] = binding.executeanonymous(string apexcode);

Answered by manisha Murakami

With the Callable interface, introduced in Winter '19 you can now build a lightweight interface for the methods you want to dynamically call from an apex  The example below is from the docs (tweaked to show dynamic method naming): Example apex string class you want to call dynamically

public class Extension implements Callable { // Actual method String concatStrings(String stringValue) { return stringValue + stringValue; } // Actual method Decimal multiplyNumbers(Decimal decimalValue) { return decimalValue * decimalValue; } // Dispatch actual methods public Object call(String action, Map args) { switch on action { when 'concatStrings' { return this.concatStrings((String)args.get('stringValue')); } when 'multiplyNumbers' { return this.multiplyNumbers((Decimal)args.get('decimalValue')); } when else { throw new ExtensionMalformedCallException('Method not implemented'); } } } public class ExtensionMalformedCallException extends Exception {} }
Unit test demonstrating the dynamic calling
@IsTest private with sharing class ExtensionCaller { @IsTest private static void givenConfiguredExtensionWhenCalledThenValidResult() { // Given String className = 'Extension'; // Variable to demonstrate setting class name String methodName = 'multiplyNumbers'; // Variable to demonstrate setting method name Decimal decimalTestValue = 10; // When Callable extension = (Callable) Type.forName(className).newInstance(); Decimal result = (Decimal) extension.call(methodName, new Map { 'decimalValue' => decimalTestValue }); // Then System.assertEquals(100, result); } }

Your Answer

Interviews

Parent Categories