Case-insensitive matching of a string to a Java enum

后端 未结 9 1511
独厮守ぢ
独厮守ぢ 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:22

    and it would implement exactly the functionality of the Day.lookup() method for any enum, without the need to re-write the same method for each enum.

    Probably you can write a utility class for doing that as the following.

    public class EnumUtil {
    
        private EnumUtil(){
            //A utility class
        }
    
        public static > T lookup(Class enumType,
                                                       String name) {
            for (T enumn : enumType.getEnumConstants()) {
                if (enumn.name().equalsIgnoreCase(name)) {
                    return enumn;
                }
            }
            return null;
        }
    
        // Just for testing
        public static void main(String[] args) {
            System.out.println(EnumUtil.lookup(Day.class, "friday"));
            System.out.println(EnumUtil.lookup(Day.class, "FrIdAy"));
        }
    
    }
    
    enum Day {
        Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
    }
    

    It would have been nice if there was a way in Java for us to extend the Enum class by implicitly adding methods just the way values() method is added but I don't think there is a way to do that.

提交回复
热议问题