Can we access class properties dynamically with Object class?

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');
System.debug(c.getX('var2'));

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


Using an internal map for this purpose has the advantage that get/set access performance doesn't degrade as more fields are added:

public class XYZ {

    private Map<String, Object> m = new Map<String, Object>();

    // "Dynamic" getter
    public Object get(String key) {
        return m.get(key);
    }

    // "Dynamic" setter
    public void put(String key, Object value) {
        m.put(key, value);
    }

    // Static access to the same data
    public String s1 {
        get { return (String) get('s1'); }
        set { put('s1', value); }
    }

    // Static access to the same data
    public Integer i2 {
        get { return (Integer) get('i2'); }
        set { put('i2', value); }
    }
}

Best to write a code generator if you want to do very much of this to avoid typo mistakes.

Tags:

Class

Apex

Code