function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Shubh2910Shubh2910 

How to create Dynamic Map for different Object in Apex

Let suppose I am getting a record in SObject type List. Now I want to create a Map dynamically. If Record are Opportunity Type then Map get created of Type Map<Id, Opportunity> , if Record are type of Account then map get created of type  Map<Id, Account>.
Similary if record are of any type then Map get created for that type of Object.
Vishwajeet kumarVishwajeet kumar
Account newObj = new Account(Name='Test Account');//variable for Account
sObject newSObj = newObj;//Sobject variable for Account
String objType = newSObj.getSObjectType().getDescribe().getName();//use it for getting object name
System.debug('Object Name ::' + objType );//output object api name

Use describe as mentioned in line 3 of above code to get Sobject type name.
Shubh2910Shubh2910
Thanks for your reply!!!

I am also getting the object Name. But now I want to create the Map for Object(suppose we got Opportunity in newSObj variable) which you got in newSObj variable. So I am trying this:

Map<Id, newSObj> testMap = new Map<Id, newSObj>();

But this is showing Error.