简体   繁体   中英

Alternatives to Enum.valueOf for a generic that doesn't extend Enum?

I have the following code

protected <T> T func(Class<T> c) {
    if (c.isEnum()) {
        try {
            return c.cast(Enum.valueOf(c, "string"));
        } catch (IllegalArgumentException e) {
            return null;
        }
    }
    return null;
}

that IDEA reports the error Wrong 1st argument type. Found: 'java.lang.Class<T>', required: 'java.lang.Class<T>' Wrong 1st argument type. Found: 'java.lang.Class<T>', required: 'java.lang.Class<T>' on in valueOf function. I can avoid this error by specifying <T extends Enum<T>> in the function header but the idea is that T can be a wide range of types, not just enums. Is it possible to get the code to compile/run without restricting T ?

I didn't use Enum.valueOf() , instead I used Class.getEnumConstants()

protected <T> T func(Class<T> c) {
    if (c.isEnum())
        for (T t : c.getEnumConstants())
            if (((Enum<?>) t).name().equals("KG"))
                return t;
    return null;
}

This way it compiles without warning, but I'm not sure if this is what you want.

Quick, unpleasant answer (I'm sure there's better ones).

You can always just cast c to Class before using it in valueOf . So

return (T) Enum.valueOf((Class) c, "string");

would work; provided you know the only Enum class that can be provided has an enum constant named string .

Probably some warnings to suppress there too...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM