I have the next code:
public String foobar(Object foo, Map<String,Object> parametersMap){
...
boolean isFoo = (boolean) parametersMap.get("is_foo");
...
}
I would expect it to throw a class cast exception (Map.get returns an Object type) but it doesn't. I'm working with java (7), spring suit and maven (all projects have language level 7). The project compiles and works well.
There is only one place where this method is called and there this param is always set (type primitive boolean). Is it possible that the compiler analyzes the flow in some way and recognize it (there for not throwing the class cast exception)?
It is the Java autoboxing at work
You put a primitive boolean
into your Map
and it gets converted into a Boolean
. Once you get it out, you can use it's primitive or Object form without casting (or with casting if you prefer).
Thse two pieces of code are equivalent:
myMap.put("is_foo", true);
and
myMap.put("is_foo", Boolean.TRUE);