Skip to main content

Dynamic calling of Apex classes

 


Dynamic class invocation in Apex refers to the ability to call methods or instantiate classes at runtime using their names as strings, rather than hardcoding the specific class name or method. This provides flexibility and makes it easier to handle various objects and behaviors in a generic way.

Key Concepts:

  1. Dynamic Class Instantiation:

    • Apex allows you to instantiate classes dynamically based on their names. This is particularly useful when you have to interact with different types of classes but don't want to explicitly reference each class.

  2. Dynamic Method Invocation:

    • You can invoke methods dynamically by using Type and Method classes, and the Reflection mechanism in Apex, enabling you to call methods based on the method name at runtime.

  3. Use of Type.forName:

    • Apex has the Type class, which allows you to reference a class by its string name. Using Type.forName('Namespace.ClassName'), you can dynamically create objects or invoke methods.

  4. Polymorphism:

    • You can leverage polymorphism to call methods on different classes that implement the same interface, even if the exact class isn’t known until runtime.


Why Use Dynamic Class Invocation in Apex?

Dynamic class invocation provides flexibility and scalability in your code. Here are a few reasons to use it:

  1. Handling Multiple Classes:

    • In scenarios where you need to process different sObjects (like Account, Contact, etc.) dynamically, you can use dynamic class invocation to call a handler for each specific sObject type without explicitly writing the code for each type.

    Example:

    • Instead of writing separate methods for processing Account, Contact, Opportunity, etc., you can dynamically call the respective handler classes based on the type of the incoming object.

  2. Scalability:

    • When the business logic requires flexibility to handle many types of records (sObjects) that implement a common interface, dynamic invocation allows you to scale easily by adding new classes without changing existing code.

  3. Reduced Code Duplication:

    • Dynamic invocations allow you to avoid duplicating code for each class. Instead of writing individual logic for each class, you can write a generic handler and invoke class methods dynamically based on the object type.

  4. Flexibility in Test Environments:

    • It can be useful in testing and writing reusable components. For instance, if you want to dynamically test multiple classes without changing code for each, you can invoke the appropriate class or method dynamically based on the context.


Demo Code:

Interface class:

public interface globalHandler {
    void processRecord(List<SObject> record);
}

Create Handler Classes:

AccountHandler
public class AccountHandler implements globalHandler{
    public void processRecord(List<SObject> record) {
        System.debug('Processing AccountRecords: ' + record);
    }
}

ContactHandler

public class ContactHandler implements globalHandler{
    public void processRecord(List<SObject> record) {
        System.debug('Processing Contact Record: ' + record);
    }
}

Map Handlers Dynamically:

public DynamicClassInvoker invokeHandler(List<SObject> sObj) {
        for(sObject sObjectValue  : sObj){
            String sObjectType = sObjectValue.getSObjectType().getDescribe().getName();
             if (handlerMap.containsKey(sObjectType)) {
                handlerMap.get(sObjectType).processRecord(sObj);
            } else {
                System.debug('No handler found for sObject type: ' + sObjectType);
            }
        }

        return this;
    }

Calling Code:

List<sObject> passingParam = new List<sObject>(); List<Contact> contactRecords = [SELECT Id FROM Contact]; List<Account> accounts = [SELECT Id from Account LIMIT 10]; passingParam.addAll(accounts); passingParam.addAll(contacts); DynamicClassInvoker callGlobal = new DynamicClassInvoker(); callGlobal.invokeHandler(passingParam);


How It Works:

  1. Invoke Handler:

    • The invokeHandler method receives a List<SObject> and iterates through it.

    • For each SObject in the list, the method checks its type (sObjectType).

    • It then checks if a handler exists for that type in the handlerMap. If found, it calls processRecord on the handler and passes the entire list of SObjects (sObjList).

  2. Handler Classes:

    • Each handler (like AccountHandler or ContactHandler) now processes a list of SObjects.

    • Inside the processRecord method, we loop through the passed list and cast the SObject to the appropriate object type (Account or Contact).

    • This allows the handler to work with multiple records at once.

  3. Why the List:

    • By passing the entire List<SObject> to the handler, you enable the handler to process multiple records at once, which is often more efficient (e.g., when performing DML operations or aggregating data for a batch).


Comments

Popular Posts

Top 100 Most common used Apex Method in Salesforce

  Here are 100 more Apex methods in Salesforce: 1.       insert: Inserts records into the database. 2.       update: Updates records in the database. 3.       delete: Deletes records from the database. 4.       upsert: Updates or inserts records into the database. 5.       query: Retrieves records from the database using SOQL. 6.       getContent: Retrieves the content of a document or attachment. 7.       getContentAsPDF: Generates a PDF file from a Visualforce page or HTML content. 8.       addError: Adds a custom error message to a record and prevents saving. 9.       start: Initiates processing in batch Apex. 10.    execute: Processes a batch of records in batch Apex. 11.    finish: Finalizes processing in batch Apex....

How to create ICS/Calendar File | Helps you to download the calendar invites

  Want to know how to create ICS(Internet Calendar Scheduling) file for Business purpose....đź‘€    ICS (Internet Calendar Scheduling) file is a calendar file saved in a universal calendar format used by several email and calendar programs, including Microsoft Outlook, Google Calendar, Notes and Apple Calendar. It enables users to publish and share calendar information on the web and over email. Lets see the code. The code is written in lwc(Lightning web component). HTML:   <template> <div class="login-container"> <h1 style="size: 14px;"><b>Create ICS File</b></h1> <div class="form-group"> <lightning-input type="datetime" name="input1" value={EventEndValue} onchange={startDate} label="Enter Start date/time value" ></lightning-input> </div> <div class="form-group"> <lightning-input type="...

Salesforce Flow Updates – Spring’25 Release

  In this blog, we’ll dive into the Salesforce Flow Updates introduced in the Spring ’25 Release. We’ll explore their practical applications and how they enhance user experiences. This release emphasizes improved usability, efficiency, and functionality in Salesforce Flows. With upgrades like enhanced Flow Builder features, reactive screen actions, and progress indicators, Spring ’25 takes automation to the next level. Let’s explore each Salesforce Flow Updates 1. View Flow Versions Side by Side The Spring ’25 update introduces the ability to open flow versions in separate tabs directly within the Flow Builder. This feature allows you to compare different versions side by side on the same canvas, streamlining the debugging process and improving efficiency. 2.Smarter Search in Resource Picker The resource picker now features enhanced nested search functionality, simplifying the process of finding the right resources. Whether you're looking for record variables, custom labels, or glo...

Sharing records by Apex in Salesforce

  Greetings, everyone! In today's session, we'll delve into the topic of sharing records within an Apex class. As we're aware, there exist various methods through which we can accomplish the sharing of records. We engage in record sharing primarily when the object's Organization Wide Default (OWD) settings are set to private. Sharing settings come into play when certain predefined criteria are met, allowing us to extend access to records to designated groups or roles. In cases where intricate logic is involved, manual sharing is employed. While this approach proves beneficial for specific records, instances where a multitude of records require automated handling, Apex sharing becomes the preferred solution. Salesforce offers a 'Share' object for each type of object, with distinct naming conventions: For standard objects, it's 'StandardobjectName+Share', such as 'AccountShare' for the 'Account' object. Custom objects follow the pattern...

Capture Real time data using CDC(Change Data Capture) in Salesforce | SF Fact #05

Change Data Capture (CDC) enables receiving near-real-time updates for Salesforce records and synchronizing them with an external data store. CDC publishes change events that reflect modifications to Salesforce records, including new records, updates, deletions, and undeletions. These events can be subscribed to in a Lightning Web Component (LWC) using the Emp API. To meet the business requirement of creating a task whenever a user manually changes an opportunity's status to "Closed Won," use CDC events and a generic LWC on the opportunity record page. This solution avoids the need for Apex triggers or record-triggered flows. How to enable CDC? Go to setup Search Change Data Capture Add Entities The  lightning/empApi  module provides access to methods for subscribing to a streaming channel and listening to event messages. All streaming channels are supported, including channels for platform events, PushTopic events, generic events, and Change Data Capture events. This co...