I have a method that accepts an Object. In one use case, the method accepts a HashMap<String, String>
and sets each value to the property of the corresponding key name.
public void addHelper(Object object) {
if (object instanceof HashMap) {
HashMap<String, String> hashMap = (HashMap<String, String>) object;
this.foo = hashMap.get("foo");
this.bar = hashMap.get("bar");
}
}
This class adheres to a particular interface, so adding setters for those properties is not an option.
My question is, how can I check the type cast here?
HashMap<String, String> hashMap = (HashMap<String, String>) object;
Thanks in advance!
SOLUTION
Thanks to the answer from @drobert, here is my updated code:
public void addHelper(Object object) {
if (object instanceof Map) {
Map map = (Map) object;
if (map.containsKey("foo")) this.foo = map.get("foo").toString();
if (map.containsKey("bar")) this.bar = map.get("bar").toString();
}
}