1

I'm looking to create a generic wrapper APEX class with few property fields (string type for now). Here is what my class would look like:

public class wCustomWrapper {
    public String customProp1;
    public String customProp2;
    public String customProp3;
    ... (this property list could extend to 100 odd properties) ...
}

I have consumed this in a method where I'm trying to populate the customProp1, customProp2, ... field values.

In that method, I'm now looking to make this dynamic like populating as sObject fields, where I could just do sObject.put(fieldName, value), instead of hard referencing each property individually.

Can this be done in any way for a wrapper class?

1

1 Answer 1

3

If you want one generic put method to work, you basically have two options. The first would be to tuck your attributes in a Map.

public class MyWrapper
{
    public Map<String, Object> attributes;
    public MyWrapper put(String key, Object value)
    {
        attributes.put(key, value);
        return this;
    }
}

The other approach would be to use one giant switch statement. Probably not worth the effort, as it doesn't scale well and you'd have to update it every time you add a property.

public MyWrapper put(String key, Object value)
{
    switch on key
    {
        when 'field1' { attribute1 = value; }
        // etc.
    }
}

Alternatively, when I see code similarly structured I would just pass in the SObject instance and set all relevant fields at once. If the wrapper represents just one object, usually in the constructor.

public class MyWrapper
{
    public MyWrapper(MyObject__c record)
    {
        attribute1 = record.Field1__c;
        // etc.
    }
}
3
  • Don't think I could use sObject instance as the response I'm trapping in wrapper is a JSON External API Response. And have similar thoughts like yours on the other approach of using Map variable within the class.
    – VarunC
    Commented Jul 23, 2021 at 17:20
  • 1
    I didn't say you'd put it as an attribute, but rather a parameter in the constructor. You wouldn't change your wrapper structure using that approach.
    – Adrian Larson
    Commented Jul 23, 2021 at 17:40
  • Thnx. Yes I misunderstood earlier. Seems much friendlier approach like that. Gonna use it now :-)
    – VarunC
    Commented Jul 23, 2021 at 18:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .