When the new Apex type methods were added in Summer '12, it was possible to do
Type t = Type.forName('MyClass');
MyClass newObj = (MyClass)t.newInstance();
What is the equivalent when I want to instantiate a List of such a class for which I only know the name at runtime?
I am also trying to create multiple records using JSON.deserialize
. I think the answer to the earlier question may also help me with creating a List of such objects with JSON.deserialize(jsonStringOfSeveralObjects, appropriateListClass)
.
Note: I am able to use a Type method to create a record of a custom object like this:
Type oType = Type.forName(‘MySobjectName’);
sObject rec = (sObject) JSON.deserialize(jsonString, oType);
But when the JSON string is an array of objects I am unable to use a method similar to the example shown below:
List<InvoiceStatement> deserializedInvoices =
(List<InvoiceStatement>)JSON.deserialize(JSONString, List<InvoiceStatement>.class);
Can you suggest the right format to use with List<>
to create multiple records? I am specifically looking for corresponding substitutes for List<InvoiceStatement>
and List<InvoiceStatement>.class
that can be dynamically determined.
Best Answer
The trick is to deserialize into a
List<SObject>
. This works for me:Output: