+ 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");