# In Apex, can I detect if an Object is a Map, regardless of parameterized types?

When I declare a Map, I need to give the types, e.g.:

Map<Id, SObject> sObjectByIdMap = new Map<Id, SObject>();


We can assign map to generic values as Objects:

Object value = sObjectByIdMap;


I can check if the value is an instance of Map;

Boolean isSObjectByIdMap = (value instanceof Map<Id, SObject>);


But what if I just want to know whether the object is an instance of a Map?

Unfortunately, this won't compile:

Boolean isMap = (value instanceof Map);


Is there some way I can do this?

• What exactly are you trying to do with this? This may actually be an X-Y problem, given the limitations of polymorphic features of Apex Code. It might be worth your time to ask a question that directly attacks the problem you're trying to solve. I do have this answer and this answer that go into more details about the problem (and workarounds), but you might not need this feature anyways. – sfdcfox May 10 '18 at 14:49
• At the moment, the question is rather academic... I'm just trying to explore and understand the quirks and limitations of SFDC's broken type system, especially regarding Maps since they can be incredibly useful. – Brian Kessler May 10 '18 at 15:39

It's ugly and hackish, but this works:

public class MAP_Detector {
public Boolean isMap(Object obj) {
String str = String.valueOf(obj);
String firstCharacter = str.substring(0, 1);
String lastCharacter = str.substring(str.length() - 1, str.length());
return !(obj instanceof String)
&& '{'.equals(firstCharacter)
&& '}'.equals(lastCharacter);
}
}


The syntax for intanceOf is bit wrong, the right syntax is:

Boolean isMap = value instanceof Map<Object,Object>;


Alternatively,

You can try to typecast it into the map, if it fails it's not. You can create an utility method for it.

public static boolean isMap(Object input){
try{
Map<Object,Object> tempmap = (Map<Object,Object>)input;
return true;

}catch(Exception e){
return false
}

}

• Unfortunately, while Map<String, SObject> SHOULD be an instance of Map<Object, Object>, it actually is not. If you tests this solution, you'll find isMap is FALSE, whereas the desired result would be true. – Brian Kessler May 10 '18 at 9:52
• Oh bummer.. never expected this. – Pranay Jaiswal May 10 '18 at 10:06
• Yeah, Types often don't work as expected in Apex. :-( – Brian Kessler May 10 '18 at 11:17