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

前端 未结 3 599
野性不改
野性不改 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 06:55

    If you think about what has to happen inside valueOf, you'll realize that your code cannot possibly work as written. Enum.valueOf needs as an argument an instance of an actual enum class; it then simply iterates through the values() for that class looking for a match.

    Because of type erasure, generics won't work in your code. No actual type is being passed into Enum.valueOf.

提交回复
热议问题