0

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?

1 Answer 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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.