Can we access class properties dynamically with Object class?

Is it possible to access Apex class properties dynamically? While we can create Object‘s, and assign any other class to an Object, I’m not sure how I can access the properties of these Object‘s. Can anyone provide some documentation or references to code which would allow me to do this?


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'); 


Unfortunately, that feature is not supported via default Apex.
But there is something, which is possible to do in this case — create custom get method, and extend your classes from your base custom object (CoreObject in example below):

public abstract class CoreObject{
    public Object getX(String param_name){
            String json_instance = Json.serialize(this);
            Map<String, Object> untyped_instance;
            untyped_instance= (Map<String, Object>)JSON.deserializeUntyped(json_instance);
            return untyped_instance.get(param_name);

So, in that case, for every class, where you need generic get method, you can define your class as ancestor of this class, like

public class MyMegaClass extends CoreObject {
    public String var1;
    public Integer var2;

And use it like:

MyMegaClass c = new MyMegaClass();
c.var1 = 'test1';
c.var2 = 12;

String generic_value1 = (String)c.getX('var1');

Warning: In case if class has self reference, that may cause issue with JSON loop serialization/deserialization.

Source : Link , Question Author : Shrivaths Kulkarni , Answer Author : kurunve

Leave a Comment