2

Disclaimer: not very strong with generics.

enum WeekDays {
   SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}
enum Months {
   JANUARY, FEBRAURY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER;
}
enum Directions {
   East, West, North, South, Up, Down
}

Let's say I have above enums and there is a service which sends me random Strings.

I need to verify if the targeted String response is a valid enum value or not.

I was thinking of coding of something on lines as below:

static <T> boolean isValidEnum(String value, T enumClass ){
   try {
       enumClass.valueOf(value);
       return true;
   } catch (Exception e) {
   }
   return false;
}

The call would be like:

isValidEnum("TUESDAY", WeekDays)

but line enumClass.valueOf(value); is not happy about my function.

Any pointers is appreciated! TIA

3 Answers 3

2

You can rewrite it to this:

static <T extends Enum<T>> boolean isValidEnum(String value, Class<T> enumClass ){
    try {
        Enum.valueOf(enumClass, value);
        return true;
    } catch (Exception e) {
    }
    return false;
}

and

isValidEnum("TUESDAY", WeekDays.class)
Sign up to request clarification or add additional context in comments.

3 Comments

simple and elegant, missed the Enum utility completely!
Simple, but not elegant: it throws an exception every time the value is not valid
@AndreaLigios: IMHO, exceptions if raised consciously are better sometimes than taking the long path of iteration but then again, individual opinion varies!
2

You need to iterate the Enum values and check if there is a match with the value passed:

With Java 8 and newer versions:

static <T> boolean isValidEnum(String value, T enumClass ){
    return Arrays.stream(((Class) enumClass).getEnumConstants())
            .anyMatch(v -> v.toString().equals(value));
}

With older Java versions:

static <T> boolean isValidEnum(String value, T enumClass ){
    for (Object v : ((Class) enumClass).getEnumConstants()){
        if (v.toString().equals(value)) return true;
    }
    return false;
}

Comments

1

There is a library for this, you can also use that in case you don't want to implement it.

EnumUtils of org.apache.commons.lang3

EnumUtils.isValidEnum(WeekDays.class, "TUESDAY")

2 Comments

isValidEnum also does the same thing internally what i am trying to do, interest was to understand the under the hood thing!
@NoobEditor Yes I undestand, I just want let you know about the library.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.