[SalesForce] Instantiate an instance of the SObject type

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.

Best Answer

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);
        types.add(record.parentid.getsobjecttype());
    }
    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.