1

I have some code that i want to try and emulate generics for. I know there are no generics in Apex but is there something we can do instead?

Let me explain

(String) sfBorr.get('SSN__pc');

sfBorr is an sObject

This line of code will throw an exception if get() returns null. I want to create a method that will catch this error and then just return null if the field is blank but i need to cast the object at some point, which means i would need to check for null every time i assign a field.

7
  • It is hard to provide good guidance with so little context. Can you please edit your post to be more specific about what you are trying to achieve, including a more detailed scenario?
    – Adrian Larson
    Commented Feb 21, 2019 at 16:41
  • 2
    Just fyip .. (String) sfBorr.get('SSN__pc'); will actually not throw an exception but still return null, assuming sfBorr is a Map.
    – Jayant Das
    Commented Feb 21, 2019 at 16:43
  • What more would you like to know? I basically want to have a method that puts the cast in a try catch and return nulls so i can use this method for all my fields, instead of having to write the code out for every field
    – Ben Arnao
    Commented Feb 21, 2019 at 16:44
  • @JayantDas sfBorr is an sObject
    – Ben Arnao
    Commented Feb 21, 2019 at 16:46
  • @BenArnao I made an assumption that it's a Map, but still, my comments above holds good. Even if its a SObject, and as long as the field exists on the SObject, if the value doesn't return anything, the casting here won't throw an exception.
    – Jayant Das
    Commented Feb 21, 2019 at 16:48

1 Answer 1

0

Well, there is a solution.

we have getPopulatedFieldsAsMap method in Sobject

getPopulatedFieldsAsMap Returns a map of populated field names and their corresponding values. The map contains only the fields that have been populated in memory for the SObject instance.

You can use it to your advantage.

(String) sfBorr.getPopulatedFieldsAsMap().get('SSN__pc');

This won't give you Invalid Field Exception. Happy Days

1
  • What are you trying to do? I tried String id = (String) new Account().getPopulatedFieldsAsMap().get('Issd'); it works Commented Feb 21, 2019 at 19:23

You must log in to answer this question.

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