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
jaxdmasterjaxdmaster 

eval like functionality

Hi All,

 

String field = 'name';

Account acc = [select id,name from account limit 1];

acc.field = 'Jon';

 

 

I am running this code. This produces error. I want to have eval(Javascript) like functionaly in Apex. So that I can do something like this eval(acc.field) = 'Jon';

 

Thanks

 

Ankit AroraAnkit Arora

You can not bind field like this :

 

acc.field = 'Jon';

 

Name after '.' should be an API name of field in an object.

 

 

Thanks

Ankit Arora

Blog | Facebook | Blog Page

Rahul SharmaRahul Sharma

I think you want to print of view the Name = 'Jon' which you are assigining to Any Account.
If the case is something different, could you please explain some more.
Else for just to see the output, run this code:

Account acc = [select id,name from account limit 1];
acc.Name = 'Jon';
update acc;
system.debug('====Here is the name of the account which you updated with:===='+acc.Name);

Run this in system debug and see the output.

David81David81

If you are looking to dynamically change which field you are setting, you can do something like this. I added a couple debugs so you can verify the change.

 

String field = 'name';

Account acc = [select id,name from account limit 1];
system.debug('Account before = '+acc);

acc.put(field,'Jon');
system.debug('Account after = '+acc);

 

Or if you are just looking to get the value from the field then:

String fieldValue = acc.get(field);
system.debug(field + ' = ' + fieldValue);