Java: specific enums and generic Enum<?> parameters

假如想象 提交于 2019-12-03 14:17:17
  1. Eclipse compiler and javac have some differences, especially when it comes to generics. It is believed that eclipse is correct, but that doesn't matter :)

  2. Try

    public static <T extends Enum<T>> Enum<T> getEnumAttribute(Element element, String name, 
        Enum<T> defaultValue) {
       ...
    }
    

I don't know what version of Eclipse you are using but I think it is wrong here. My version reports the same error that you are seeing with Maven, which appears to be a genuine error.

The problem is that you have two wildcards ("?") in the signature of getEnumAttribute() but there is no constraint (nor is it possible to create one) that forces them to be the same. So a client could pass in an enum of one type as the default value and get an enum of a different type in return.

You can eliminate the error in the calling code by replacing both wildcards with a named type parameter:

class XMLUtils {

    @SuppressWarnings("unchecked")
    public static <E extends Enum<E>> E getEnumAttribute(Element element, String name, 
            E defaultValue) {

        if (element.hasAttribute(name)) {
            String valueName = element.getAttribute(name);
            // search for value 
            for (Enum<?> value: defaultValue.getClass().getEnumConstants())
                if (value.toString().equalsIgnoreCase(valueName))
                    return (E) value;
        }
        // not found, return default value
        return defaultValue;
    } 
}

But I don't think it's possible to eliminate the unchecked cast, because Enum<E>.getClass() returns Class<Enum<?>> so the compiler cannot tell what type of enum is contained in the enumConstants array.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!