I am trying to cast an Object to HashMap<String, Object> in a neat, robust way. So far, every way I tried produces compiler warnings or errors. What is the proper way to do it? I have checked the internet and tried the following:
HashMap<String, Object> map = (HashMap<String, Object>) object;
The code above gives an unchecked conversion warning.
HashMap<String, Object> map = new HashMap<>();
if (object instanceof Map<String, Object>){
map = (Map<String, Object>) object;
}
The code above gives an error, which says that objects cannot be compared to parameterized collections.
HashMap<String, Object> map = new HashMap<>();
if (object instanceof Map){
Map genericMap = (Map) object;
for (Object key : genericMap.keySet()){
if (key instanceof String){
map.put((String) key, genericMap.get(key));
}
else{
throw new KeyException();
}
}
}
The code above yields a warning that "Map is a raw type. References to generic type Map<K,V> should be parameterized."
So what would be the proper way to do this? Thank you in advance!
object instanceof Map, and you can then cast as(Map<String, Object>). Just understand that there are no compile-time checks for the proper types in that map, so if it contains non-string keys then you may have some truly odd behavior.class Foo { int x; String y; }, take an objectnew Foo(1, "bar") and get a map with the entries"x"` mapped to1and"y"mapped to"bar". That's going to be much more complicated than a cast. If what you actually have is aMap<String, Object>, then you should do the unsafe cast and accept that that's the best that you're going to get.Propertiesclass.