How to get all enum values in Java?

后端 未结 7 1635
独厮守ぢ
独厮守ぢ 2020-12-04 17:06

I came across this problem that I without knowing the actual enum type I need to iterate its possible values.

if (value instanceof Enum){
   Enu         


        
7条回答
  •  孤城傲影
    2020-12-04 17:50

    Enums are just like Classes in that they are typed. Your current code just checks if it is an Enum without specifying what type of Enum it is a part of.

    Because you haven't specified the type of the enum, you will have to use reflection to find out what the list of enum values is.

    You can do it like so:

    enumValue.getDeclaringClass().getEnumConstants() 
    

    This will return an array of Enum objects, with each being one of the available options.

提交回复
热议问题