Sunday, 30 December 2012

Create instance of sobject dynamically

Normally the sobject is created like “Account a = new Account();”. But if you are in situation that you don’t know which sobject is going to be instantiated ? Means it will be decided at runtime,then how we handle it .By using dynamic apex we handle it.
See the following snippet.


public SObject getNewSobject(String t)
{

 // Call global describe to get the map of string to token.
 Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();

 // Get the token for the sobject based on the type.
 Schema.SObjectType st = gd.get(t);

 // Instantiate the sobject from the token.
 Sobject s = st.newSobject();

 return s;
}

No comments:

Post a Comment

What’s the difference between Einstein Article Recommendations and Suggested Articles?

How Does Einstein Article Recommendations Work? Einstein Article Recommendations helps support agents resolve customer cases efficiently by ...