Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we Cast SObject dynamically in Salesforce(apex)?

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

like image 221
AtNeo Avatar asked Nov 23 '22 13:11

AtNeo


1 Answers

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
}
like image 75
Mukesh Saxena Avatar answered Dec 25 '22 22:12

Mukesh Saxena