Let's say I have a Contact, we'll say from Trigger.new. If I want to update its parent account, I skip a query by initializing it in memory like this.

Account acct = new Account(Id = contactInstance.AccountId);
update acct; 

Now I'm trying to apply the same idea, but with dynamic apex using the new Type class. My object name comes from a custom setting. And because in this instance I'm working with Attachment, and ParentId in this instance, and ParentId can be one of many different types, I'm really trying to avoid the DB trip for a second query. Only, it doesn't work:

Type t = Type.fromName(setting.ObjType__c);
sObject myObjInstance = t.newInstance();

An sObject Id will allow initialization, but it is not writable.

Anyone know any workarounds on this one? Or is it wait for API version 27?

1 Answer 1


The Schema.SObjectType class has a method specificially for setting an ID during sObject construction.

The second method on that listing is Schema.SObjectType.newInstance(Id), which

Constructs a new sObject of this type, with the specified ID. For the argument, pass the ID of an existing record in the database.

I believe this is exactly what you're looking for. If you need to go deeper and set other non-updateable fields in memory you may need to look into (ab)using JSON.deserialize

  • Awesome! That's what I needed. Will look into JSON abuse at some other date. :-)
    – pchittum
    Commented Oct 17, 2012 at 23:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .