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 :)
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With