function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
jhelblingjhelbling 

Reference an object field using a variable

Hello,

 

The following will work :

 

Map<ID,Account> m = new Map<ID,Account>{};
(insert values into m)
m.get(id).get("fieldName") = "a value";

 

Now I would like to use "fieldName" in the following, but it won't work :

 

Map<ID,Account> m = new Map<ID,Account>{};
m.put(id, new Account(id=id, "fieldName"="a value"));

 

Does anybody have a workaround ?

 

Is it somehow possible to create a new object by referencing a field name using a variable ?

 

Thank you very much.

 

 

 

Best Answer chosen by Admin (Salesforce Developers) 
sfdcfoxsfdcfox

You can't use variables in an SObject constructor for the field. Instead, you have to perform the action post-construction, such as:

 

m.get(id).put("fieldname","a value");