I want to create lists of sobject where sobject types will be input from a custom label or a custom metadata.

Can I create a list of sobjects in a for loop where the name of the list will be dynamic?

something like this -

for(Integer i=0; i<somesize; i++) {
List<SObject> listName*i* = new List<SObject>();
  • Your post and its title do not seem to describe very well what you want to do. You keep saying you want the name of the list to be dynamic, but it seems much more likely that you want the type of the list or the types of the records it contains are what you want to be dynamic. Could you please edit your post to make it a bit more clear? In your above post, the name of the list is i. Is that really what you want to be dynamic?
    – Adrian Larson
    May 21, 2021 at 16:26
  • If the name of the list really is what you want to make dynamic, you're going to have to make clear why as you are almost certainly facing an XY Problem.
    – Adrian Larson
    May 21, 2021 at 16:27

2 Answers 2


The type List<SObject> can hold records for any type of SObject. So the following would work, for example:

List<SObject> records = new List<SObject>();
records.add(new Account());

So you don't need to do much to support dynamically typed lists. Unless, that is, you are trying to upsert them. Then you need to use Type.forName as I outlined here.

String listType = 'List<' + sObjectType + '>';
List<SObject> castRecords = (List<SObject>)Type.forName(listType).newInstance();

But this type of casting should not be necessary for any other use case.


I just responded on your previous post.

Yes, you can use the Schema class. SObject itself is dynamic.

List<SObject> records = new List<Sobject>();
Map<String,Schema.SObjectType> gd = Schema.getGlobalDescribe(); 
for(Integer i=0; i<somesize; i++) {

If you want to split it then you can use the instance of and use Map<String, List<SObject>> where key is the API name of object.

  • @manjit I want to create different list of sobject, where the name will be dynamic. May 21, 2021 at 16:25
  • @AdrianLarson I actually already have the combined list of generic sobject and would like to split it, but don't know the sobjecttypes of the various records in the original list. May 21, 2021 at 16:28
  • But why? Let us further discuss in chat.
    – Adrian Larson
    May 21, 2021 at 16:29

You must log in to answer this question.

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