Uploaded image for project: 'Commons Lang'
  1. Commons Lang
  2. LANG-1495

Add EnumUtils getEnum() methods with default values

    XMLWordPrintableJSON

Details

    • Improvement
    • Status: Resolved
    • Trivial
    • Resolution: Fixed
    • None
    • 3.10
    • None
    • None

    Description

      I would like to add 2 overloading methods to EnumUtils, getEnum and getEnumIgnoreCase.

      Instead of returning null, if not found. In my opinion I think allowing user to set a default result is a better approach or return an Optional.
       

      public static <E extends Enum<E>> E getEnum(final Class<E> enumClass, final String enumName) {
       return getEnum(enumClass, enumName, null);
       }
      
      public static <E extends Enum<E>> E getEnum(final Class<E> enumClass, final String enumName, E defaultEnum) {
       if (enumName == null) {
       return defaultEnum;
       }
       try {
       return Enum.valueOf(enumClass, enumName);
       } catch (final IllegalArgumentException ex) {
       return defaultEnum;
       }
       }
      

        

       

      public static <E extends Enum<E>> E getEnumIgnoreCase(final Class<E> enumClass, final String enumName) {
       return getEnumIgnoreCase(enumClass, enumName, null);
       }
      public static <E extends Enum<E>> E getEnumIgnoreCase(final Class<E> enumClass, final String enumName, E defaultEnum) {
       if (enumName == null || !enumClass.isEnum()) {
       return defaultEnum;
       }
       for (final E each : enumClass.getEnumConstants()) {
       if (each.name().equalsIgnoreCase(enumName)) {
       return each;
       }
       }
       return defaultEnum;
       }
      

       

      Attachments

        Issue Links

          Activity

            People

              Unassigned Unassigned
              vlcheong Cheong Voon Leong
              Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

              Dates

                Created:
                Updated:
                Resolved:

                Time Tracking

                  Estimated:
                  Original Estimate - Not Specified
                  Not Specified
                  Remaining:
                  Remaining Estimate - 0h
                  0h
                  Logged:
                  Time Spent - 1h 20m
                  1h 20m