
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:
- Define the Wrapper Class: This class holds the data you want to pass to the method. It can contain various data types and structures.
- Create the Apex Class Method: This method will accept the wrapper class as a parameter and extract values from it.
- 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
andage
.MyClass
contains a static methodprocessWrapper
that takes aMyWrapper
object as a parameter.- The method
processWrapper
extractsname
andage
from the passedMyWrapper
instance. - Finally, we create an instance of
MyWrapper
, populate it with data, and pass it toprocessWrapper
.
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 online course, enriched with practical, real-world projects. Transform into a market-ready professional equipped with in-demand skills. Secure your spot today!