Eclipse is giving me a warning of the following form:
Type safety: Unchecked cast from Object to HashMap
This is from a call to
In this particular case, I would not store Maps into the HttpSession directly, but instead an instance of my own class, which in turn contains a Map (an implementation detail of the class). Then you can be sure that the elements in the map are of the right type.
But if you anyways want to check that the contents of the Map are of right type, you could use a code like this:
public static void main(String[] args) {
Map map = new HashMap();
map.put("a", 1);
map.put("b", 2);
Object obj = map;
Map ok = safeCastMap(obj, String.class, Integer.class);
Map error = safeCastMap(obj, String.class, String.class);
}
@SuppressWarnings({"unchecked"})
public static Map safeCastMap(Object map, Class keyType, Class valueType) {
checkMap(map);
checkMapContents(keyType, valueType, (Map, ?>) map);
return (Map) map;
}
private static void checkMap(Object map) {
checkType(Map.class, map);
}
private static void checkMapContents(Class keyType, Class valueType, Map, ?> map) {
for (Map.Entry, ?> entry : map.entrySet()) {
checkType(keyType, entry.getKey());
checkType(valueType, entry.getValue());
}
}
private static void checkType(Class expectedType, Object obj) {
if (!expectedType.isInstance(obj)) {
throw new IllegalArgumentException("Expected " + expectedType + " but was " + obj.getClass() + ": " + obj);
}
}