There's not really any way of doing this properly because the compile-time type information you want to check (i.e. String
) is not available at runtime, (i.e. when the cast actually occurs) through the process known as erasure. I think that the best way is for you to pass your deserialized collection thru some bespoke "checker":
Map<?,?> conf = deserialize(rsrc);
Map<String, String> checked = checkMap(conf, String.class, String.class);
//can use checked freely
where:
@SuppressWarnings("unchecked")
public static <K, V> Map<K,V> checkMap(Map<?,?> map, Class<? extends K> k, Class<? extends V> v) {
for (Map.Entry<?, ?> e : map) {
k.cast(e.getKey()); //will throw ClassCastException
v.cast(e.getValue());
}
return (Map<K,V>) map; //unchecked
}