How to Dynamically Access Class Properties in Apex Using Object

Question
Can Apex Class Properties Be Accessed Dynamically?
Is it possible to dynamically access properties of an Apex class? In Apex, we can create an Object
and assign any class to it, but accessing the properties of the assigned class dynamically seems unclear. Can anyone provide documentation or examples of how to achieve this functionality? Understanding how to dynamically access class properties in Apex using Object would be highly beneficial.
For example, consider the following:
public class XYZ {
public string s1 { get; set; }
public string s2 { get; set; }
}
XYZ testXyzObj = new XYZ();
Object obj = testXyzObj;
// Method does not exist or incorrect signature: [Object].get(String)
String s1 = obj.get('s1');
Answer
It is not possible to directly access class properties dynamically through the Object
class in Apex. While you can assign any class to an Object
variable, Apex does not support a method like get(String propertyName)
to dynamically retrieve a property value from an Object
.
CRS Info Solutions offers top-notch Salesforce Online Training with real-time projects, certification support, and interview coaching. Their practical approach ensures you’re fully prepared for the job!
However, there is a workaround. You can achieve dynamic property access by creating a custom base class with a generic getter method. This method serializes the object into JSON and deserializes it into an untyped map. The map can then be used to access properties dynamically by their names. Here’s how you can implement this approach:
First, define a base class with a generic getter method:
public abstract class CoreObject {
public Object getX(String paramName) {
// Serialize the current object to JSON
String jsonInstance = JSON.serialize(this);
// Deserialize the JSON into a Map<String, Object>
Map<String, Object> untypedInstance = (Map<String, Object>)JSON.deserializeUntyped(jsonInstance);
// Retrieve the property dynamically
return untypedInstance.get(paramName);
}
}
Next, create a class that extends this base class:
public class MyMegaClass extends CoreObject {
public String var1;
public Integer var2;
}
Now you can use the generic getter method to access properties dynamically:
See also: What are classes in Apex programming?
MyMegaClass c = new MyMegaClass();
c.var1 = 'test1';
c.var2 = 12;
// Access properties dynamically
String genericValue1 = (String)c.getX('var1');
System.debug('Value of var1: ' + genericValue1);
Integer genericValue2 = (Integer)c.getX('var2');
System.debug('Value of var2: ' + genericValue2);
Important Note: If the class has a self-referencing property (e.g., a field that references the object itself), it may cause issues during JSON serialization or deserialization, potentially leading to infinite loops. Care should be taken to handle such scenarios.
This approach allows for dynamic property access in Apex where direct support is not available.
Advance Your Career with Salesforce Online Training
Our Salesforce Online Training offers a dynamic, hands-on learning experience that equips you with essential skills for success in the CRM industry. The course covers key areas like Salesforce Admin, Developer, and AI, combining theoretical knowledge with practical, real-world applications. Through live projects and assignments, you’ll gain expertise in solving complex business problems using Salesforce solutions. With experienced instructors providing technical guidance and industry insights, you’ll be set for success.
In addition to comprehensive technical training, the program includes personalized mentorship, exam preparation, and interview coaching to help you stand out in a competitive job market. Access study resources, live project exposure, and continuous support throughout the course. By the end, you’ll be ready for certification exams, equipped with the skills and problem-solving abilities that employers are looking for. Start your Salesforce journey now and open the door to exciting career opportunities! Join our FREE demo class today!
Kickstart your Salesforce career and explore amazing job opportunities.!
Sign up for a FREE Demo today..!!