2

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:)

6

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');
|improve this answer|||||
  • 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/…) – James Loghry Jan 10 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 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. – James Loghry Jan 10 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 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 – James Loghry Jan 10 at 19:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.