tags:

views:

71

answers:

1

I have a class EnumConverter<T extends Enum<?>> that converts strings to the correct enum constant for the enum T (I can't use Enum.valueOf). I construct instances of this class in a factory method like this:

public static <T extends Enum<?>> EnumConverter<T> getInstance(Class<T> enumClass) {
    return new EnumConverter<T>(enumClass.getEnumConstants());
}

This works, but now I want to cache EnumConverter instances to make sure there is only one per enum, i.e. with a Map, and my problem is how to declare this Map. The closest I have come is this:

private static final Map<Class<?>, EnumConverter<? extends Enum<?>>>

But I get an error if I try to return a value from this Map from my factory method:

Type mismatch: cannot convert from EnumConverter<capture#1-of ? extends Enum<?>> to EnumConverter<T>

Any ideas?

+2  A: 

As you want to store different sub types in the map, the compiler can't know which actual subtype you are receiving. I think you have to add a cast:

public static <T extends Enum<?>> EnumConverter<T> getInstance(Class<T> enumClass) {
    return (EnumConverter<T>) cache.get(enumClass);
}
tkr
Thanks, that works! But I still get a warning: `Type safety: Unchecked cast from EnumConverter<capture#3-of ? extends Enum<?>> to EnumConverter<T>`. But this is probably not possible to address due to type erasure?
hakos
The answer is indeed `@SuppressWarnings("unchecked")`: http://stackoverflow.com/questions/262367/type-safety-unchecked-cast
hakos