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
nimbusprojectnimbusproject 

Cast types dynamically similar to Reflection (or reflective programming)

Hey guys is there any way to dynamically cast a type so that I can take a List<sObject> and cast which ever entry I am currently using to the type just knowing its type (maybe stored in a String or something)

 

I am trying to do something like

 

String being_used = 'Contact'; List<sObject> store; store = Database.query('select Name from' + being_used); List<String> test = new List<String>(); for(sObject s : store) { test.add( (being_used)s.get('Name')); // Or (being_used)s.Name; }

 Basically I just need a way that I can store multiple sObject types (such as Account, Contact, Opportunities, etc..) in a List<sObject> and then access their field values, which it seems you have to cast into the type before accessing any field besides Id with a generic sObject.

 

Best Answer chosen by Admin (Salesforce Developers) 
mtbclimbermtbclimber

You shouldn't need to cast a concrete sobject sobject to get field values:

 

SObject s = database.query('select name from contact limit 1'); Object name = s.get('name');

 

You can learn more in the documentation, specifically the chapter on Dynamic Apex.