You need to sign in to do that
Don't have an account?

How to instantiate custom/standard object using describe call.
Hi,
I have a requirement in which I need to instantiate an object (Custom or standard) by the objectName (A String).
for example : If I send the "Account" string as parameter, I want an object (Account object) of this type should be instantiate and get assigned to SObject variable.
Is there any way we can archive this ?
Thanks & Regards,
Anand Agrawal.
Good idea but I'd leverage our describe and dynamic semantics so you can get out of trying to keep this code consistent with your org metadata. Here's the sample with tests :
Check out the Dynamic Apex chapter in the Apex documentation for more info.
All Answers
You can achieve this by using a Factory pattern.
public class SObjectFactory
{
public static SObject buildObject(String objName)
{
if(objName == 'Account')
{
return new Account();
}
if(objName == 'Opportunity')
{
return new Opportunity();
}
if(objName == 'CustomObj__c')
{
return new CustomObj__c;
}
}
}
Good idea but I'd leverage our describe and dynamic semantics so you can get out of trying to keep this code consistent with your org metadata. Here's the sample with tests :
Check out the Dynamic Apex chapter in the Apex documentation for more info.
Yeah, the Schema Describe is even better than the static approach I gave. Forgot about that when I was typing it up. :) Good Catch.
Only caveat - You are limited to 100 Describe calls in a Context.
So make sure to Bulkify your code and use a Singleton pattern if necessary to catch the Describe calls in memory.
Thank you very much Andrew. That is really helpful and what I was looking for. thanks again for your contribution.
Thanks to Cory who tried figure this out for me. :)
Gr8 help...!! :)
Thanks,
Anand Agrawal.