I wonder if it is possible to write a method that will handle casting of undefined types like:
Precondition:
Map<String, Object> map = new HashMap<>();
List<String> l = List.of("value");
map.put("key", l);
Method call:
List<String> strings = convert("key", List.class, String.class);
convert method itself:
public <V, C extends Collection<V>> C<V> getCollection(String key, Class<C> collType, Class<V> objectType) {
return (C<V>) map.get(key);
}
But statement C< V > doesn't compile and gives me an error: Type 'C' doesn't have type parameters.
Any ideas?
Java uses target typing in type inference which means the expected type on the right-hand side of an assignment can be leveraged for this purpose.
However, to take advantage of it an unchecked cast is needed:
You could then get the typed entry out of the map:
However, because of type erasure of Java generics, the type parameter is not checked at runtime. So while this will throw a
ClassCastException:This will execute without any complaint, and you won't get a
ClassCastExceptionuntil you try to extract the values from the list: