I have the following piece of code where I wish to cast a certain object to a specific SObjectType.

public static void someMethod(Object obj, Schema.DescribeSObjectResult objectType){
        Map<String, Object>v = ((objectType) obj).getPopulatedFieldsAsMap();

where objectType should be something like Account, Custom_Obj__c etc.:

Map<String, Object>v = ((Account) obj).getPopulatedFieldsAsMap();

But passing Schema.DescribeSObjectResult does not work. What is the data type that should be passed in the method?


1 Answer 1


You can't dynamically cast in Apex. Fortunately, here, you don't need to.

Type obj as an Sobject value, rather than Object. The getPopulatedFieldsAsMap() method is defined on the sObject class, so you can call it regardless of what concrete sObject your method receives.

If you do need to write distinct logic for different sObject types, you can use a switch on construction. Example from the linked document:

switch on sobject {
   when Account a {
       System.debug('account ' + a);
   when Contact c {
       System.debug('contact ' + c);
   when null {
   when else {
  • Object obj is not something I can control, but I added (Sobject) obj and it worked. Hope I'm not violating any ethics. May 12, 2020 at 1:30

You must log in to answer this question.

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