apache commons EnumUtils.isValidEnum(EnumClass, stringValue) shows wierd behavior

7.9k views Asked by At

I have an Enum as given below:

public enum EnumClass {
ValOne("ValOne."), ValTwo("ValTwo."), valone("ValOne"), valtwo("ValTwo."), ValThree("ValThree"), ValFour("ValFour"), ValFive("ValFive"), ValSix("ValSix");
private String enumValue;
private EnumClass(String value) {
    this.enumValue = value;
}
@Override
public String toString() {
    return this.enumValue;
}}

I am using

org.apache.commons.lang3.EnumUtils..isValidEnum(EnumClass, stringValue)

I use the enum values and not the name of the enum class
(eg: "ValTwo." instead of the enum "ValTwo")
When I check if a given String value is equal to an Enum value, it always checks on the name of the enum object (is. "ValTwo") instead of Enum.toString. I was under the impression that it checks the value instead of enum object itself.
The weird behavior is that, initially when I tested the code, it checked on the value than the name. But, after rebuilding the app, it was checking the name. No code change was done which might've effected the change.
Any inputs would be deeply appreciated.
Thanks in advance!!

2

There are 2 answers

0
NixRam On BEST ANSWER

I think I know the answer. I checked the source code of EnumUtils.isValidEnum

    public static <E extends Enum<E>> boolean isValidEnum(Class<E> enumClass, String enumName) {
    if (enumName == null) {
        return false;
    }
    try {
        Enum.valueOf(enumClass, enumName);
        return true;
    } catch (IllegalArgumentException ex) {
        return false;
    }
}

Looks like it checks the Enum members and not the value returned.!

0
Venkat On

This may help you,

 boolean isValid(Class enumClass, String value) {
            return Arrays.stream(enumClass.getEnumConstants()).anyMatch((e) -> value.equals(
                    e.toString()));
        }