2

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?

hakos
  • 250
  • 2
  • 9

1 Answers1

2

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
  • 1,241
  • 1
  • 7
  • 26
  • Thanks, that works! But I still get a warning: `Type safety: Unchecked cast from EnumConverter> to EnumConverter`. But this is probably not possible to address due to type erasure? – hakos Jul 23 '10 at 10:36
  • The answer is indeed `@SuppressWarnings("unchecked")`: http://stackoverflow.com/questions/262367/type-safety-unchecked-cast – hakos Jul 23 '10 at 10:51