开发者

Static factory method with generics

开发者 https://www.devze.com 2023-01-08 07:43 出处:网络
I have a class EnumConverter<T extends Enum<?>> that converts strings to the co开发者_运维技巧rrect enum constant for the enum T (I can\'t use Enum.valueOf). I construct instances of this

I have a class EnumConverter<T extends Enum<?>> that converts strings to the co开发者_运维技巧rrect 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?


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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消