Enum.valueOf throws a warning for unknown type of class that extends Enum?

前端 未结 3 482
野性不改
野性不改 2021-01-07 06:33

Give this:

Class enumClass = ...; // being passed in from a constructor
Enum e = Enum.valueOf(enumClass, aString); // produces a warnin         


        
3条回答
  •  伪装坚强ぢ
    2021-01-07 07:05

    Both Enum and Class are generic. So if you don't want any warnings:

    class Foo>{
        Class enumClass;
        T e = Enum.valueOf(enumClass, str);
    }
    

    Or you can have a generic method:

    public > T getEnumValue(Class clazz, String name) {
        T e = Enum.valueOf(clazz, name);
        return e;
    }
    

    But if you don't use generics, you are using raw types, and therefore the compiler issues warnings - there is no option apart from suppressing them.

提交回复
热议问题