Reputation: 183
Assume we have multiple different untyped Map<?,?>
maps of unknown type keys and unknown type values and it is known that there are Map<String,Object>
and Map<Integer,Object>
maps among them.
Whether is there a way to check and distinct and safely cast them into appropriate typed maps?
Upvotes: 1
Views: 1634
Reputation: 3890
try
if(((Map.Entry)map.entrySet().iterator().next()).getKey().getClass().getName().equals("java.lang.Integer")){
System.out.println("Map<Integer,Object>");
}else{
System.out.println("Map<String,Object>");
}
Upvotes: 1
Reputation: 220
Due to type erasure, it's not possible to determine the type parameters of a generic class at runtime. However, if the maps are populated, and you know that each Map is either a Map(String, Object) or a Map(Integer, Object), you could simply inspect the first key from each Map and cast accordingly.
What's the use-case for this?
Upvotes: 1