I think what's below is the kind of code you were looking for.
public class DynamicSObjectCreation {
public static sObject createObject(String typeName) {
Schema.SObjectType targetType = Schema.getGlobalDescribe().get(typeName);
if (targetType == null) {
// throw an exception
}
// Instantiate an sObject with the type passed in as an argument
// at run time.
return targetType.newSObject();
}
}
Test Class
@isTest
public class DynamicSObjectCreationTest {
static testmethod void testObjectCreation() {
String typeName = 'Account';
String acctName = 'Acme';
test.startTest();
// Create a new sObject by passing the sObject type as an argument.
Account a = (Account)createObject(typeName);
System.assertEquals(typeName, String.valueOf(a.getSobjectType()));
// Set the account name and insert the account.
a.Name = acctName;
insert a;
// Verify the new sObject got inserted.
Account[] b = [SELECT Name from Account WHERE Name = :acctName];
system.assert(b.size() > 0);
test.stopTest();
}
}
When tested with a string passed to it, this method fails. I modified the code to create a list of type string and received a compile error message that essentially translated to: an instance of an sObject is never an instance of a String
.
I've concluded that dynamic instantiation of primitive sObject doesn't work using schema describe based operations. That makes sense to me when I take time to pause to think about it. Obviously, an sObject of type string does not have a name nor does it have an Id that one can pass to it, like one can to a record on a Standard or Custom object. All an sObject of type string is going to have is an array of strings and the name of the list that's assigned to it when running as code. There's nothing else to make it unique. One can create it on the fly by simply declaring it. There's no need to use any kind of a schema call to create it. These will of course continue to have a unique type
to identify them by.
If it was a record
containing fields with nothing but strings
, then it would be a custom object
that would still have a unique Id
associated with it. That is a different matter entirely and would be returned in a getGlobalDescribe
method.
I think what you'll want to do is create a series of methods with if statements that call the correct method if the string matches the type of primitive sObject list you want to create. I believe I've seen similar code, but don't have it at hand at the moment and you seem to have that part handled anyway.