0

I have a list of SObject and SObjectType parameters passed to a method

sObjectTypeRecord in the below method contains Lead.SObjectType,it can also contain any other SObjectType like Account.SObjectType or Contact.SObjectType.

In the method I want the SObject list typecasted to the SObjectType passed to the method. Is that possible?

 public static void getDetails(List<SObject> newSObjectList, SObjectType sObjectTypeRecord){
 }

1 Answer 1

3

Nope, afraid not.

When it comes to dynamic typing like this, Apex is very limited. The best you'll be able to do is to get a List<SObject>, which you're already passing into your method.

If you use additional classes/methods where you can statically declare the type, then it is possible to cast a List<SObject> into a more specific type.

example

public class AClass{
    // This method acts as a dispatcher, using the SObjectType to tell us which method
    //   to actually run
    public static void getDetails(List<SObject> newSObjectList, SObjectType sObjectTypeRecord){
        // A map can be a handy way to avoid long if-else if chains
        Map<SObjectType, HandleSObject> dispatchMap = new Map<SObjectType, HandleSObject>{
            Account.SObjectType => new HandleAccount(),
            Case.SObjectType => new HandleCase(),
            // and so on...
        };

        // Since everything in the map values implements HandleSObject, we can just
        //   call the method defined by the interface
        dispatchMap.get(sObjectTypeRecord).getSObjDetail(newSObjectList);
    }

    public interface HandleSObject{
        public void getSObjDetail(List<SObject> sobjList);
    }

    public class HandleAccount implements HandleSObject{
        public void getSObjDetail(List<SObject> sobjList){
            // In these inner classes, we only have one SObject type that we need
            //   to worry about.
            // So we are able to declare the concrete type statically
            List<Account> accountList = (List<Account>)sobjList;
        }
    }

    public class HandleCase implements HandleSObject{
        public void getSObjDetail(List<SObject> sobjList){
            List<Case> caseList = (List<Case>)sobjList;
        }
    }
}

Which would then be used like this

// Even though we're casting this as a List<SObject>, using List<Account> in 
//   Type.forName() is enough for us to be able to cast this as a List<Account>
//   later on (at the point where we know that it must be a List<Account> and 
//   not a list of some other SObject type)
List<SObject> mySObjList = (List<SObject>)(Type.forName('List<Account>').newInstance());

AClass.getDetails(mySObjList, Account.SObjectType);

You must log in to answer this question.

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