Case-insensitive matching of a string to a Java enum

后端 未结 9 1515
独厮守ぢ
独厮守ぢ 2020-12-24 10:59

Java provides a valueOf() method for every Enum object, so given an enum like

public enum Day {
         


        
相关标签:
9条回答
  • 2020-12-24 11:26

    I am using this way for case-insensitive matching of a string to a java enum Day[] days = Day.values(); for(Day day: days) { System.out.println("MONDAY".equalsIgnoreCase(day.name())); }

    0 讨论(0)
  • 2020-12-24 11:28

    Starting from version 3.8 apache commons-lang EnumUtils has two handy methods for this:

    • getEnumIgnoreCase(final Class<E> enumClass, final String enumName)
    • isValidEnumIgnoreCase(final Class<E> enumClass, final String enumName)
    0 讨论(0)
  • 2020-12-24 11:28

    You can use Class's getEnumConstants() method, which returns an array of all the enum types, if the Class represents an enum, or null if not.

    Returns the elements of this enum class or null if this Class object does not represent an enum type.

    Your enhanced for loop line would look like this:

    for (T d : enumType.getEnumConstants()) {
    
    0 讨论(0)
提交回复
热议问题