Get Enum Instance from Class<? extends Enum> using String value?

后端 未结 4 1588
时光取名叫无心
时光取名叫无心 2020-12-15 17:24

I\'m finding it difficult to put the exact question into words, so I\'ll just give an example.

I have two Enum types:

enum Shape {
    C         


        
4条回答
  •  遥遥无期
    2020-12-15 17:30

     public static > T getInstance(final String value, final Class enumClass) {
         return Enum.valueOf(enumClass, value);
     }
    

    And the method is to be used as:

    final Shape shape = getInstance("CAT", Shape.class);
    

    Then again, you can always use

    final Shape shape = Shape.valueOf("CAT");
    

    which is a shortcut for

    Enum.valueOf(Shape.class, "CAT");
    

提交回复
热议问题