'Java create map between classes and classes with generic type of key classes
I have a class Saver<T> with one generic type argument <T>. In my Saver<T> class, I'm attempting to define the following static map:
public abstract class Saver<T> {
private static final Map<Class<E>, Class<? extends Saver<E>>> DEFAULT_SAVERS = new HashMap<>();
}
Of course, this gives me an error because the compiler doesn't know what E is. How can I create this map? The map should have Classes for keys, and Savers with that class as its generic type as its values. Is this possible? How can I do this?
Solution 1:[1]
There's no typesafe way to declare it. You'll have to use wildcards and control how it's accessed to prevent heap pollution:
private static Map<Class<?>, Saver<?>> DEFAULT_SAVERS = new HashMap<>();
public static <T> void put(Class<T> clazz, Saver<T> saver) {
DEFAULT_SAVERS.put(clazz, saver);
}
public static <T> Saver<T> get(Class<T> clazz) {
return (Saver<T>)DEFAULT_SAVERS.get(clazz);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | shmosel |
