How to find out if an Object is a collection or single value?

I have some dynamic SOQL code in which I’d like to identify whether a method argument is a collection or a single value:

SObject[] query(SObjectType sobType, String field, Object data) {
    // Want to know if data is a collection e.g. set or list
    // that requires an "in" or a single value that requires
    // an "=" in the query. (May also need to use separate bind variables.)

I note that the sort of check shown immediately below seems to require an exact match for the type of the collection (Id in this case to return true) which is not what I want:

Object o = new Set<Id>();
System.debug(o instanceof Set<Id>);

Is there a simple way to make this determination?

(Yes there are various other ways to code this; checking first to see if there is a direct solution.)


Looks like great caution is needed when using instanceof with collections.


If you are using a data binding, you do not need to know. = will work in either case, so you don’t need to ever switch to IN for the use case you outline above. I used the following code in Execute Anonymous to demonstrate:

Object searchTerm = new Set<String> { 'test', 'test2' };
SObjectField field = Account.Name;
SObjectType sObjectType = Account.sObjectType;

    'SELECT Id FROM ' + sObjectType + ' WHERE ' + field + ' = :searchTerm'

I also used searchTerm = 'test'; and the query ran just fine in either case.

Source : Link , Question Author : Keith C , Answer Author : Adrian Larson

Leave a Comment