I have a utility method that that works on lists of SObjects that are normally of one type:
private void oneType() {
Contact[] contacts = new Contact[] {};
contacts.add(new Contact(...));
contacts.add(new Contact(...));
upsertUtility(contacts);
}
but occasionally I want to use the method with lists of mixed SObject type:
private void mixedType() {
SObject[] mixed = new SObject[] {};
mixed.add(new Contact(...));
mixed.add(new Account(...));
upsertUtility(mixed);
}
For the second mixed case this error occurs:
DML on generic List only allowed for insert, update or delete
because of a known issue in the platform.
So I'm wondering if it is possible to detect the unsupported case for the rare occasions it comes up and use upsert
for the common case. So the question is can the type of the list be detected i.e. what code could replace the ???
in this code:
private void upsertUtility(SObject[] sobs) {
if (???) insertUpdate(sobs);
else upsert sobs;
}
private void insertUpdate(SObject[] sobs) {
SObject[] updates = new SObject[] {};
SObject[] inserts = new SObject[] {};
for (SObject sob : sobs) {
if (sob.Id != null) updates.add(sob);
else inserts.add(sob);
}
update updates;
insert inserts;
}
Concrete lists of SObject types are subclasses of lists of SObject so instanceof
doesn't help and there is no way I can see to get the type of a list. But I may be missing something.