Duffydake
Duffydake

Reputation: 917

How to pass different enums as argument?

I have some enums, all different, and I want to create a function that can find or not if a string is one of enum variable name (not sure it's really understandable).

enum MYENUM {
  ONE,
  TWO;
}

enum MYENUM1 {
  RED,
  GREEN;
}

I want to do this (this is just for the example, my enum are more complicated):

if(isInEnum(MYENUM, "one")) ...
if(isInEnum(MYENUM1, "one")) ...

isinEnum function (the code is bad, it's just for understanding):

boolean isinEnum(enum enumeration, String search) {
  for(enum en : enumeration.values()){
    if(en.name().equalsIgnoreCase(search)) return true;
  }
  return false;
}

Is this kind of thing possible?

I think not, according to what I can read on the web, but maybe someone has a solution to do this, instead of making one loop for each enum.

Upvotes: 2

Views: 2736

Answers (3)

Andrew White
Andrew White

Reputation: 53496

Here is a way using reflection...

public class EnumFinder {

    public static <T extends Enum<T>>  boolean isInEnum(Class<T> clazz, String name) {
        for (T e : clazz.getEnumConstants()) {
            if (e.name().equalsIgnoreCase(name)) {
                return true;
            }
        }

        return false;
    }

    public static void main(String[] argv) {
        System.out.println(isInEnum(MYENUM.class, "one"));   // true
        System.out.println(isInEnum(MYENUM1.class, "one"));  // false
    }
}

Your attempt in your answer was actually very close. The only difference is that Java needs an instance of the defining class in order to answers questions about an unknown type dynamically at runtime.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726599

This may not be the cleanest solution because it uses exceptions in the normal program flow, but it is certainly short, because it avoids the loop:

boolean isinEnum(Class<T> enumClass, String search) {
    try {
        Enum.valueOf(enumClass, search);
        return true;
    } catch (IllegalArgumentException iae) {
        return false;
    }
}

Upvotes: 1

hEADcRASH
hEADcRASH

Reputation: 1915

Your question is a bit tough to understand, but I think I get the gist of it.

You might be making things a lot tougher on yourself than necessary.

Take a look at Java's map interface / data structure (in java.util) and see if that moves you closer to your solution:

java.util Interface Map<K,V>

If not, repost with any leg-work you've done and I'll see if I can help ya' further. ;-)

Upvotes: 0

Related Questions