Salesforce: Instantiating an SObject Dynamically at Run-time

I’m sure a lot of you have this documented somewhere but I’ve recently discovered that it’s quite difficult to find an obvious reference to this knowledge on the interwobbles. So how would you create a Generic SObject at run-time? It’s rather easy thankfully: If you require this type of functionality quite often I’d suggest putting it in a utility class.

Lists of SObjects and Classes – By value or reference?

I found a quirky bug in my code some time back, and realised that the cause of the bug was quite a useful Apex feature viz. SObjects and Apex classes are passed by reference and not value.

What does this mean you say? Let’s start by defining what passing by value means.

In a nutshell, if you pass a variable to a method and it’s a Force.com primitive type(Integer, String etc.) it will be passed by value meaning that the value of the variable and not the variable itself is passed to the method

Read more

Instantiating an empty list of SObjects

You’re building a dynamic Apex class so general you’re thinking about promoting it to colonel. You’ve slogged through the Salesforce documentation on the topic, a feat in itself, but are having issues instantiating an empty list of SObjects to be processed in some way. If you attempt to do this in the seemingly Salesforce manner i.e. [code language=”java”] List<SObject> sobjects = new List<SObject>(); [/code] You will receive the following error: Compile error: Only concrete SObject lists can be created This can be rather frustrating as this type of data structure is one of the more commonly used. There are however 3 workarounds, one slightly more elegant than the rest. NB myObject is a SObject. [code language=”java”] List<SObject> sobjects = Database.query(‘select id from ‘ + myObject.getSObjectType() +’ where id=null’); [/code] [code language=”java”] String searchquery=’FIND\’xxx\’IN ALL FIELDS RETURNING ‘+ myObject.getSObjectType() +'(name)’; List<List<SObject> searchList=search.query(searchquery); List<SObject> sobjects = searchlist[0]; [/code] or finally you could …

Read more