Friday, April 24, 2020

Dynamically access any variable in an instance class

In this blog post, I will show you how to access any variable on an instance of an Apex class dynamically.

This is something useful when you want to make dynamic feature which are based on setting, especialy when doing ISV stuffs.

The code is as simple as below:

public class Employee {
    public String employeeId;
    public String firstname;
    public String lastname;
    public String username;
    public String profileUrl;

    public Object getValue(String variableName) {
        String jsonString = toJSON();
        Map<String, Object> untyped_instance;
        untyped_instance = 
            (Map<String, Object>)JSON.deserializeUntyped(jsonString);
        return untyped_instance.get(variableName);
    }
    
    public string toJSON() {
        return JSON.serialize(this);
    }
}

Example:

Employee emp = new Employee();
emp.employeeId = 'test';
emp.firstname = 'kevan';
emp.lastname = 'moothien';
emp.username = 'kevanmoothien';
emp.profileUrl = 'https://picsum.photos/200/300';

system.debug(emp.getValue('firstname')); // returns kevan
system.debug(emp.getValue('lastname')); // returns moothien

Here is a use case where this kind of integration can be used based on the above code.
Suppose you have to develop a custom related list lightning component which would be used on several layout. But on each layout, it has to display different columns.

To achieve this, we would think of different component and hardcoded variable. But, this can be done by simply having a Custom Metadata type to save the setting of each layout and the related list custom component can simply display the columns value dynamically using the above code based on the setting provided in the Lighting app builder.

Hope this is useful to you trailblazers.

Cheers :)

No comments:

Post a Comment