Is there a way to instantiate an SObject without a SOQL query?

This works :

Type t = Type.forName('Account' );
Account  o =  (Account) t.newInstance();

But this doesn't :

Type t = Type.forName('Sobject' );
Sobject  o =  (Sobject) t.newInstance();

SObject appears to be an abstract type / interface. Given that, is there a way to instantiate an SObject with a 'concrete' Id without using the GlobalDescribe / 3-letter prefix trick.

For example , consider a trigger on FeedItem where the ParentId is of unknown type.


SObject is an abstract class. You can't directly instantiate SObject itself, as the platform requires that the contained SObject knows what type it is (because of the validation for which fields are legal, what data type each field has, etc).

You can determine what type of SObject you're working with by checking the ID. For example, a FeedItem trigger might look like this:

trigger X on FeedItem (after insert) {
    map<id, sobject> parents = new map<id, sobject>();
    set<sobjecttype> types = new set<sobjecttype>();
    for(FeedItem record: Trigger.new) {
        parents.put(record.parentid, null);
    for(sobjecttype stype: types) {
        parents.putall(query.fortype(stype, parents.keyset()));
    // Do something with the data you now have

I left out the "Query.forType" function in this post, because one should build the queries according to one's needs.


Following on @sfdcfox, you don't even need to have a record to use the getsobjecttype() method. For instance, the code below resolves to "Opportunity":

Id foo = '0061h00000GpoOSAAZ';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.