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
What did I do wrong? How do I resolve the issue?
You are getting this message because getBean returns an Object reference and you are casting it to the correct type. Java 1.5 gives you a warning. That's the nature of using Java 1.5 or better with code that works like this. Spring has the typesafe version
on its todo list.
A warning is just that. A warning. Sometimes warnings are irrelevant, sometimes they're not. They're used to call your attention to something that the compiler thinks could be a problem, but may not be.
In the case of casts, it's always going to give a warning in this case. If you are absolutely certain that a particular cast will be safe, then you should consider adding an annotation like this (I'm not sure of the syntax) just before the line:
Another solution, if you find yourself casting the same object a lot and you don't want to litter your code with
@SupressWarnings("unchecked")
, would be to create a method with the annotation. This way you're centralizing the cast, and hopefully reducing the possibility for error.