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
RamyaKrishnaRamyaKrishna 

Reg: Converting any type to Sobject

Hi,

I have a list of objects which are in String format.

List<String> obj=new List<String>();

in "obj" list i have E__c, F__c and some more object names.

sObject  objData=new E__c();

But here, in the place of E__c i need to change the object names dynamically based on list values(I need to convert List<String> type to sObject type dynamically ).

How can it possible.

please suggest me.

 

Regards:

Ramya.

 

Best Answer chosen by Admin (Salesforce Developers) 
Ritesh AswaneyRitesh Aswaney

You cannot cast a String to an sObject.

 

 

I'm guessing your requirement intends to say that corresponding to each string, there is a type of Sobject.

 

So for eg 'Account' => Account

 

in which case you can use

 

String sObjectName = 'E__c';
Schema.SObjectType t  = Schema.getGlobalDescribe().get(sObjectName);
SObject s = t.newSObject();

 

 

All Answers

RamyaKrishnaRamyaKrishna

Hi,

        String str='E__c';
        Object obj=(Object)str;
        sObject sobj=(sObject)obj;
        system.debug('SSS'+sobj);

I used these lines. It gives an exception like,

14:37:04.059|EXCEPTION_THROWN|[7]|System.TypeException: Invalid conversion from runtime type String to SObject

But in my requirement i need to convert string type into sObject type. 

Is it possible? 

Please send answer..

 

Regards:

Ramya


Ritesh AswaneyRitesh Aswaney

You cannot cast a String to an sObject.

 

 

I'm guessing your requirement intends to say that corresponding to each string, there is a type of Sobject.

 

So for eg 'Account' => Account

 

in which case you can use

 

String sObjectName = 'E__c';
Schema.SObjectType t  = Schema.getGlobalDescribe().get(sObjectName);
SObject s = t.newSObject();

 

 

This was selected as the best answer
iffuiffu

I am also trying to fetch all the custom fields to a corresponding custom object.

 

 

List<Schema.SObjectType> gd = Schema.getGlobalDescribe().Values(); 

customObjects = f.getDescribe().getName();

Map<String, Schema.SObjectField> cFieldMap = Schema.SObjectType.customObjects.fields.getMap();

 

When I am hardcoding the customObjects string value with sobject then it works fine but this way, it doesn't

Any clue?

iffuiffu

I got the solution to manipulate this.

 

I actually developed a wrapper class, which will catch all the custom objects and their relevant custom fields in maps and then using all of them in a query by Database.query method.

 

Thanks!