I would call a method defined as
<T> void foo(Class<? extends Collection<T>>)
but the compiler does not allow me to pass
foo(ArrayList<Integer>.class);
What is the syntax for getting a class type of a generic type?
I implement the general case when I have
Map<Key, Collection<Value>>
and want to insert the value into the collection. If the collection does not exist, it must create a new one and paste the value into it. So far, I have the following code, but with security type warnings:
public static <K, V, C extends Collection<V>> boolean addToMappedCollectionNotNull(Map<K, C> aMap, K key, V element, Class<? extends Collection> type) {
C collection = aMap.get(key);
if (collection == null) {
try {
collection = (C)type.newInstance();
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
}
aMap.put(key, collection);
}
return collection.add(element);
}
Jordi source
share