Java enum elements with spaces?

后端 未结 8 725
夕颜
夕颜 2020-12-02 19:07

Im working on java, I have created an enum as follows:

public enum myEnum
{
    india,
    russian,
    england,
    north America
}

Above

8条回答
  •  难免孤独
    2020-12-02 19:27

    just make your own valueOf like function in your enum class. Replace spaces with underscores. name your enum constants like this "north_america("North America")". If the method fails to find your enum it just returns the parameter.

    public  static String valueOfOrDefault(String myValue) {
    //replace space with underscore so it matches enum name
            String value=myValue.toUpperCase().replaceAll("\\s", "_");
            for(myEnum type : myEnum.class.getEnumConstants()) {
              if(type.name().equalsIgnoreCase(value)) {
                return type.toString();
              }
            }
            return myValue;
          }
    

提交回复
热议问题