How to get an enum value from a string value in Java?

前端 未结 27 2224
旧巷少年郎
旧巷少年郎 2020-11-21 10:53

Say I have an enum which is just

public enum Blah {
    A, B, C, D
}

and I would like to find the enum value of a string, for example

27条回答
  •  逝去的感伤
    2020-11-21 11:47

    As a switch-version has not been mentioned yet I introduce it (reusing OP's enum):

      private enum Blah {
        A, B, C, D;
    
        public static Blah byName(String name) {
          switch (name) {
            case "A":
              return A;
            case "B":
              return B;
            case "C":
              return C;
            case "D":
              return D;
            default:
              throw new IllegalArgumentException(
                "No enum constant " + Blah.class.getCanonicalName() + "." + name);
          }
        }
      }
    

    Since this don't give any additional value to the valueOf(String name) method, it only makes sense to define an additional method if we want have a different behavior. If we don't want to raise an IllegalArgumentException we can change the implementation to:

      private enum Blah {
        A, B, C, D;
    
        public static Blah valueOfOrDefault(String name, Blah defaultValue) {
          switch (name) {
            case "A":
              return A;
            case "B":
              return B;
            case "C":
              return C;
            case "D":
              return D;
            default:
              if (defaultValue == null) {
                throw new NullPointerException();
              }
              return defaultValue;
          }
        }
      }
    

    By providing a default value we keep the contract of Enum.valueOf(String name) without throwing an IllegalArgumentException in that manner that in no case null is returned. Therefore we throw a NullPointerException if the name is null and in case of default if defaultValue is null. That's how valueOfOrDefault works.

    This approach adopts the design of the Map-Interface which provides a method Map.getOrDefault(Object key, V defaultValue) as of Java 8.

提交回复
热议问题