6

I have an object instance of a sObject, for example Product.

Product2 x = new Product2();

Now I can access the field of object like that

x.Name = 'Bruce Wayne';

My questions is about this

.Name

part.

Is there any workaround to access field of our sObject with a String? What I mean

String s ='Name';
x.s = 'Bruce Wayne';

I have a certain Field API's in Custom Metadata and I need access only fields from this Metadata. I can retrieve them via SOQL, but what then? I have strings and can't do anything more. I have already tried converting String to schemaField sObject, but it does not work since after a dot operator (x.) the Apex automatically treat everything as a hardcoded field API value.

Thanks:)

1 Answer 1

10

You can use the SObject.put method to write to a field using its name:

Product2 record = new Product2();
record.put('Name', 'some value');

Similarly, if you would like to retrieve a value from a field, you can use SObject.get:

Object value = record.get('Name');
// OR
String name = (String)record.get('Name');
6
  • 1
    You'll have to cast the field though, so the correct syntax is (String)record.get('Name') or record.get('Name') != null ? (String)record.get('Name') : null; (More info here: developer.salesforce.com/docs/atlas.en-us.apexcode.meta/…) Jan 10, 2020 at 17:58
  • 1
    @JamesLoghry Please do not advocate record.get('Name') != null? (String)record.get('Name'): null; ... (String)record.get('Name') is always sufficient, and this design can cause significant performance problems in highly dynamic code.
    – sfdcfox
    Jan 10, 2020 at 18:30
  • There's a potential that Name can be null (for instance if you don't query the field in SOQL, or you can upsert with a null name in rare occasions, but it would be prudent to check for null in custom or standard fields as well. Although it might not be the most performant thing per se, it's better than throwing a null pointer exception when you cast from an Object to the proper field type. So yes, I'll continue "advocating" for null checks, because programming. Jan 10, 2020 at 19:38
  • 1
    Casting a null does not throw NPE. You can quite easily verify with an anonymous script. Object foo; String bar = (String)foo;
    – Adrian Larson
    Jan 10, 2020 at 19:39
  • Yep, you're right. Still would need to check for nulls in other cases such as calling methods on the fields like Name, but you're right on the casting piece. My bad Jan 10, 2020 at 19:45

You must log in to answer this question.

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