2

Is there a way to dynamically assign values to apex variables much like sObjects out of the box?

sObject.put('field', 'data');

Or is the only way to get this effect to create a function for it like below?

public class Thing{
    
    public String description;
    
    public void put(String field, String value){
        if(field.equalsIgnoreCase('description')){
            this.description = value;
        }
    }
}
4
  • 1
    What's your use case? This isn't really a language feature but you can get close by using a Map<String, Object> or using JSON and pairing that with JSON.deserialize
    – nbrown
    Commented Mar 22, 2021 at 12:45
  • We are using Map<String, Object> for our intermediate object but I need to finalise them at some point to an aura enabled object and was wanting to do something like for(String s : SomeMap.keySet()){ object.put(s,SomeMap.get(s)); } Commented Mar 22, 2021 at 13:38
  • 1
    Check this one -- salesforce.stackexchange.com/questions/135891/…
    – kurunve
    Commented Mar 22, 2021 at 13:53
  • @kurunve ah that's a great way. Commented Mar 22, 2021 at 15:15

1 Answer 1

4

We don't have a proper java.lang.Reflection package that allows us to write arbitrary variables dynamically, so it's not possible to use something like the put method on a user-defined class (Apex code we write). In the most usual case, what you probably want is a Map for storing arbitrary keys and data. You can also use JSON.deserialize to map fields automatically, but only to entire objects at a time.

Of course, you can use a method like what you suggest, but a proper way to do this would be to use a switch statement:

public void setItem(String key, Object value) {
  switch on key?.toLowerCase() {
    when 'field1' {
      var1 = (Integer)value;
    }
    when 'field2' {
      var2 = (String)value;
    }
    /* etc */
    when else {
      throw new IllegalArgumentException('Unexpected field: '+key);
    }
  }
}

P.S. You shouldn't use equalsIgnoreCase ever, as it is not null safe and is functionally the same as just writing == (this operator is case-insensitive for Strings in Apex).

3
  • It was just a quick example class I whipped up, but yes, switches would work better. We use maps already for our intermediate steps, but I need to cast them into an aura-enabled class. Commented Mar 22, 2021 at 14:00
  • @KarlLivesey JSON.deserialize is your friend in those cases. Or, alternatively, just use the Maps directly. It's perfectly legal to pass in and return Maps in AuraEnabled methods.
    – sfdcfox
    Commented Mar 22, 2021 at 14:41
  • doesn't seem to for returns for flow actions though which is what we are using for this and there are some extra values in there which are not part of the aura object so I feel that JSON.deserialize would have issues although I have yet to try Commented Mar 22, 2021 at 15:11

You must log in to answer this question.

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