Java – Type safety: Unchecked cast

javaspringtype-safetyunchecked

In my spring application context file, I have something like:

<util:map id="someMap" map-class="java.util.HashMap" key-type="java.lang.String" value-type="java.lang.String">
    <entry key="some_key" value="some value" />
    <entry key="some_key_2" value="some value" />   
</util:map>

In java class, the implementation looks like:

private Map<String, String> someMap = new HashMap<String, String>();
someMap = (HashMap<String, String>)getApplicationContext().getBean("someMap");

In Eclipse, I see a warning that says:

Type safety: Unchecked cast from Object to HashMap<String,String>

What went wrong?

Best Answer

The problem is that a cast is a runtime check - but due to type erasure, at runtime there's actually no difference between a HashMap<String,String> and HashMap<Foo,Bar> for any other Foo and Bar.

Use @SuppressWarnings("unchecked") and hold your nose. Oh, and campaign for reified generics in Java :)