Java泛型问题:类型参数E不在其范围内

时间:2021-04-09 16:31:19

i've got a question about generics. I have this method which does not compile at all. The compiler tells me: type parameter E is not within its bound. I've usually no problem in understanding compiler errors, but this one is quite tricky. Maybe my knowledge about generics need to improve. :-) Can anyone tell me whats wrong?

我有一个关于泛型的问题。我有一个根本不编译的方法。编译器告诉我:类型参数E不在它的范围内。在理解编译器错误方面我通常没有问题,但是这个问题相当棘手。也许我的泛型知识需要提高。谁能告诉我出什么事了?

public static <E extends Enum & StringConvertableEnum<E>> Map<String, E> map(Class<E> enumClass) {
    Map<String, E> mapping = new HashMap<String, E>();

    EnumSet<E> set = EnumSet.allOf(enumClass);

    for(E enumConstant : set) {
        mapping.put(enumConstant.getStringValue(), enumConstant);
    }

    return mapping;
}

This is the definition of StringConvertableEnum:

这是StringConvertableEnum的定义:

public interface StringConvertableEnum<E extends Enum> {
    public E getEnumFromStringValue(String string);
    public String getStringValue();
}

1 个解决方案

#1


9  

You need to change your declaration to E extends Enum<E>

您需要将声明更改为E扩展Enum

Edit, sorry had to step away, the full declaration I mean is:

编辑,不好意思我得走开,我的意思是完整的声明是:

public static <E extends Enum<E> & StringConvertableEnum<E>> Map<String, E> map(Class<E> enumClass) {

#1


9  

You need to change your declaration to E extends Enum<E>

您需要将声明更改为E扩展Enum

Edit, sorry had to step away, the full declaration I mean is:

编辑,不好意思我得走开,我的意思是完整的声明是:

public static <E extends Enum<E> & StringConvertableEnum<E>> Map<String, E> map(Class<E> enumClass) {