Reputation: 945
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)?
Upvotes: 0
Views: 212
Reputation: 61558
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);
Upvotes: 2
Reputation: 691
A ClassCastException would only happen at runtime (not at compile time), and only if the actual instance you're trying to cast is not castable to that type. So for example:
parametersMap.put("is_foo", true);
parametersMap.put("is_bar", 5);
boolean isFoo = (boolean) parametersMap.get("is_foo"); // This would work fine.
boolean isBar = (boolean) parametersMap.get("is_bar"); // This would throw an exception.
All of that would compile fine; you'd only have a problem at runtime.
Adding onto kostja's answer about the Java autoboxing, when you do this:
boolean isFoo = (boolean) parametersMap.get("is_foo");
the value you're getting out of the map is a Boolean object, and Java automatically unboxes it into a boolean primitive.
Upvotes: 2