6

Is it possible to Cast SObject dynamically?

Example :

I know we can do this :

(Account) Sobject

But I want to do this as the return type of sObject changes based on certain parameters.

(Dynamically Passing the Name) SObject

Any Kind of way around will be helpful... Thanks in advance :)

AtNeo
  • 61
  • 1
  • 2
  • 1
    I believe that the short answer is no, because you still have to assign it to a strongly-typed variable. – ScottW Sep 14 '14 at 13:34
  • Not direct casting, but you can play with some extension using the Type class? http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_type.htm – geekymartian Sep 15 '14 at 01:22
  • 1
    The Type class only allows you to instantiate a new class based on a type. It does not allow you to recast an already instantiated object. – ScottW Sep 15 '14 at 13:26
  • Here is the similar to your question - http://salesforce.stackexchange.com/questions/89087/type-class-and-casting-to-sobject , maybe it will be helpful for you – Hleb Apr 11 '17 at 09:55

2 Answers2

1

Yes, you can do it. For example -

Class ABC {

   public static List<Object> method1(String sObjectType){
      List<Object> records = new List<Object>();
      if(sObjectType == 'Account'){
          records = [SELECT Id, Name FROM Account];
      } else if(sObjectType == 'Account'){
          records = [SELECT Id, Name FROM Contact];
      }
      return records;
   }

}

You can check the sObject Type of List -

if(records instanceof List<Account>){
  // your code here
} else if(records instanceof List<Contact>){
  // your code here
}
Mukesh Saxena
  • 146
  • 2
  • 7
0

Unfortunately, no. I ran into this recently while writing a TestFactory class. The best I could do was cast the responses back into the expected type in the code that was calling the TestFactory's methods.

Shane10101
  • 103
  • 2