Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if enum type contains constant with given name

I have multiple enums in my code:

public enum First { a, b, c, d; }

public enum Second { e, f, g; }

I want to have one method that checks to see if a value is present in any enum using valueOf() without writing one for each enum type. For example (this code does not run):

public boolean enumTypeContains(Enum e, String s) {
    try {
        e.valueOf(s);
    } catch (IllegalArgumentException iae) {
        return false;
    }
    return true;
}

Usage:

enumTypeContains(First,"a"); // returns true
enumTypeContains(Second,"b"); // returns false

Any ideas on how to do something like this?

like image 942
BugsPray Avatar asked Jul 27 '11 20:07

BugsPray


People also ask

Is enum type or constant?

An enum type is a special data type that enables for a variable to be a set of predefined constants.

How do you check if a String is present in an enum?

EnumUtils class of Apache Commons Lang. The EnumUtils class has a method called isValidEnum whichChecks if the specified name is a valid enum for the class. It returns a boolean true if the String is contained in the Enum class, and a boolean false otherwise.


1 Answers

This should work:

public <E extends Enum<E>> boolean enumTypeContains(Class<E> e, String s) {
    try {
        Enum.valueOf(e, s);
        return true;
    }
    catch(IllegalArgumentException ex) {
        return false;
    }
}

You then have to call it by

enumTypeContains(First.class, "a");

I'm not sure if simply searching through the values (like in the answer from jinguy) might be faster than creating and throwing an exception, though. This will depend on how often you will get false, how many constants you have, and how long the stack trace is (e.g. how deep this is called).

If you need this often (for the same enum), it might be better to create once a HashSet or a HashMap mapping the names to the enum values.

like image 88
Paŭlo Ebermann Avatar answered Oct 06 '22 00:10

Paŭlo Ebermann