Class EnumValueOfHelper<E extends Enum<E>>

  • Type Parameters:
    E - Enum that will make use of this helper class

    public class EnumValueOfHelper<E extends Enum<E>>
    extends Object
    Provides a valueOf(String) method as a replacement for the implicitly declared enum function valueOf(String), which has the advantage of not throwing exceptions when the name argument is null or cannot be found in the enum's values. The valueOf(String) method performs a case-insensitive lookup of a corresponding enum name, and a default value can be specified for when there is no matching name.

    Usage:

     public enum Pet {
         CAT,
         DOG;
    
         private static final EnumValueOfHelper<Pets> helper = new EnumValueOfHelper<>(values(), DOG);
    
         public static Pet getPet(final String name) {
              return helper.valueOf(name);
         }
     }
     
    • Constructor Detail

      • EnumValueOfHelper

        public EnumValueOfHelper​(E[] values)
        Constructor with null default value.
        Parameters:
        values - One or more enum values
      • EnumValueOfHelper

        public EnumValueOfHelper​(E[] values,
                                 E defaultValue)
        Constructor with an explicit default value.
        Parameters:
        values - One or more enum values
        defaultValue - Default value or null
    • Method Detail

      • valueOf

        public E valueOf​(String name)
        Fast lookup of EnumValueOfHelper by its name.
        Parameters:
        name - Case-insensitive name of an enum value, or null
        Returns:
        Requested value or the default value if not found