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

后端 未结 4 1595
时光取名叫无心
时光取名叫无心 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:44

    Since you have an idea of what class you're looking for you can just ask the enum if it knows what you're interested in:

    public enum MyColor
    {
      RED  ("red", Color.RED),
      BLUE ("blue", Color.BLUE),
      TAUPE ("brownish", new COLOR(80,64,77));
    
      private final String _name;
      private final Color _color;
    
      MyColor(String name, Color color)
      {
        _name = name;
        _color = color;
      }
    
      public static Color parseColor(String colorName)
      {
        for (MyColor mc : MyColor.values())
        {
          if (mc._name.equalsIgnoreCase(colorName))
            return mc._color;
        }
        return null;
      }
    }
    

    However, plugging strings into multiple enums looking for a fit compromises the type safety you get with enums. If you map "red" to both MyColor.RED and NuclearThreatWarningLevel.RED then you may, at the very least, end up with the wrong class. At the worst you could end up in your underground bunker for 6 months waiting for the air to clear, when all you wanted was a car painted red :)

    It would be better to redesign this area of your code if possible so you don't have to convert a string to an instance of one of several classes dynamically. If you expand your answer to include the problem you're trying to solve perhaps the SO community will have some ideas.

提交回复
热议问题