How to extract values of a wrapper class passed as parameters to a apex class method?

How to extract values of a wrapper class passed as parameters to a apex class method?

On February 25, 2024, Posted by , In Interview Questions,Salesforce, With Comments Off on How to extract values of a wrapper class passed as parameters to a apex class method?

In Salesforce Apex, extracting values from a wrapper class passed as parameters to a class method is quite straightforward. A wrapper class in Apex is a custom class that developers define to group together different elements in a single unit. This is particularly useful when you want to deal with multiple data types or structures in a unified way.

Here’s a step-by-step guide with a code example:

  1. Define the Wrapper Class: This class holds the data you want to pass to the method. It can contain various data types and structures.
  2. Create the Apex Class Method: This method will accept the wrapper class as a parameter and extract values from it.
  3. Call the Method with the Wrapper Class Instance: Create an instance of the wrapper class, populate it with data, and then pass it to the method.

Here’s an example:

// Define a Wrapper Class
public class MyWrapper {
    public String name;
    public Integer age;

    public MyWrapper(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
}

// Apex Class with a Method to Extract Values
public class MyClass {

    // Method accepting a Wrapper Class instance
    public static void processWrapper(MyWrapper wrapper) {
        // Extracting values from the wrapper
        String extractedName = wrapper.name;
        Integer extractedAge = wrapper.age;

        // Example processing
        System.debug('Name: ' + extractedName + ', Age: ' + extractedAge);
    }
}

// Example of calling the method
MyWrapper wrapperInstance = new MyWrapper('John Doe', 30);
MyClass.processWrapper(wrapperInstance);

In this example:

  • MyWrapper is a simple wrapper class with two properties: name and age .
  • MyClass contains a static method processWrapper that takes a MyWrapper object as a parameter.
  • The method processWrapper extracts name and age from the passed MyWrapper instance.
  • Finally, we create an instance of MyWrapper , populate it with data, and pass it to processWrapper .

Remember, the wrapper class can be as complex as needed, containing various data types and even collections like Lists or Maps. This approach is particularly useful for handling complex data structures in a clean and organized manner.

Enhance Your Career Prospects with Salesforce CRM: Register for Our Complimentary Demo Session! Dive into our comprehensive Salesforce beginner course, enriched with practical, real-world projects. Transform into a market-ready professional equipped with in-demand skills. Secure your spot today!

Comments are closed.