Java: Check if enum contains a given string?

后端 未结 29 1520
一个人的身影
一个人的身影 2020-12-02 03:59

Here\'s my problem - I\'m looking for (if it even exists) the enum equivalent of ArrayList.contains();.

Here\'s a sample of my code problem:

<         


        
29条回答
  •  借酒劲吻你
    2020-12-02 04:46

    This approach can be used to check any Enum, you can add it to an Utils class:

    public static > boolean enumContains(Class enumerator, String value)
    {
        for (T c : enumerator.getEnumConstants()) {
            if (c.name().equals(value)) {
                return true;
            }
        }
        return false;
    }
    

    Use it this way:

    boolean isContained = Utils.enumContains(choices.class, "value");
    

提交回复
热议问题