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