+ Start a Discussion

Dynamic instantiation of sObject type?

Is there a method of dynamically setting the type of sObject from a generic?


sObject myObj = new sObject();

and then later in code set the type from a string? The goal is to allow the user to specify the object and filed being manipulated by the Apex class. I already have code to allow a dynamic field name, but the sObject definition is giving me trouble.




 works somewhat but it returns a generic sObject and needs to be recast before it can be of any use.



Message Edited by Vintara on 03-20-2009 01:59 PM

I'm looking for the same thing. Using a string of the objectname, can I instantiate a sobject of that type. I continued to snoop around. This page has some sample code in there that may help you.


dyamic apex-flexible


For example I wanted my code to work with more than just the Task object type. The sample below gets field names.


I replaced:






Schema.getGlobalDescribe().get(listObjectName ).getDescribe().fields.getMap().values()

 where listObjectName is the object's name (string) eg.'Task'




The problem I'm having is custom class instantiation.


SObject myObj = Schema.getGlobalDescribe().get('Contact').newSObject();

The above works for recasting a single object dynamically (just replace 'Contact' with any string), but an object as a property of a class seems more complex. What's more the front end code will look at something like the following and complain that it cant find the display fields I'm referencing.


public class myClass{
public Double dist{ get; set; }
public SOBject zObj{ get; set; }

public List<myClass> data{ get; set; }


myClass tmp = new myClass();
tmp.zObj = Schema.getGlobalDescribe().get('Contact').newSObject();
// set contact data


<apex:pageBlockTable value="{!data}" var="item" >
<apex:column value="{!item.zObj.FirstName}"/>


 This generates the error Unknown property 'SObject.FirstName'  because the Visual Force page checks the prototype for the fields, and even though resulting list has the correct properties the prototype does not.


Message Edited by Vintara on 03-22-2009 11:02 PM
Sanchivan SivadasanSanchivan Sivadasan

I am having the same issue. Did you get a solution? thanks.