1

So I am able to return the sobject of a list like so:

//sobjectlist = list of records passed into fuction.


Schema.SObjectType sotype = sobjectList.getsObjectType();

Now this gives me sotype with stores the actual type of sobject passed in. I was trying to do the following:

List<sObject> output = (List<sObject>)soType.newInstance();

Which gives me the following error:

Method does not exist or incorrect signature: [Schema.SObjectType].newInstance()

If it's possible, my ultimate goal is to do something like this:

List<SObject> output = (List<SObject>)getSObjectType(sobjectList).newInstance();

But this tosses the following error:

Method does not exist or incorrect signature: getSObjectType(List)

Is there a way to dynamically detect the type of a list and then create a new instance of it in one line? I'm at a loss as to what I am getting wrong....

1 Answer 1

1

If you have a List<SObject> and you want another List of the same type, use clone:

public List<SObject> getNewList(List<SObject> input)
{
    List<SObject> newList = input.clone();
    newList.clear();
    return newList;
}

If you want to instantiate a List<SObject> given an SObjectType, you will have to construct the Type yourself. The Type class does have an instance method named newInstance.

public List<SObject> getNewList(SObjectType listType)
{
    String typeName = 'List<' + listType + '>';
    return (List<SObject>)Type.forName(typeName).newInstance();
}

This latter does allow for a one-line approach if you desire (simply don't cache typeName). If you wanted to accept a List<SObject> parameter, you can still adopt this approach in one line:

public List<SObject> getNewList(List<SObject> input)
{
    return (List<SObject>)Type.forName('List<' + input.getSObjectType() + '>').newInstance();
}

From an SObjectType, you can instantiate a single record with the newSObject method:

public SObject getNewRecord(SObjectType sObjectType)
{
    return sObjectType.newSObject();
}

Or, if you really wanted to use Type and newInstance, you can get its Type using the static Type.forName method:

public SObject getNewRecord(SObjectType sObjectType)
{
    return (SObject)Type.forName(String.valueOf(sObjectType)).newInstance();
}
2
  • This is exactly what I was looking for. Thank you for the multiple examples as well. I wasn't dead set on any one way of accomplishing the goal, so this is very helpful. Thanks Adrian!
    – Genko
    Nov 17, 2016 at 18:46
  • Quick Note: When I try example 3 it's returning the following error: `Return value must be of type: List<SObject>' Edit: So is #2
    – Genko
    Nov 17, 2016 at 19:11

You must log in to answer this question.

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