Reputation: 4034
Let say I have two enum classes which implement a Foo
interface
public enum Enum1 implements Foo {
ENUM1_CONST1,
ENUM1_CONST2;
}
public enum Enum2 implements Foo {
ENUM2_CONST1,
ENUM2_CONST2;
}
How can I create a type-safe implementation of a method that takes a string as a parameter which string matches any of the enum constant's name and returns a Foo instance which could be any of the constants from both enum definitions.
In other words:
Foo foo1 = holyGrailMethod("ENUM1_CONST1");
Foo foo2 = holyGrailMethod("ENUM1_CONST2");
Foo foo3 = holyGrailMethod("ENUM2_CONST1");
Foo foo4 = holyGrailMethod("ENUM2_CONST2");
Upvotes: 0
Views: 587
Reputation: 124215
Just iterate over all your enum types (you can place them in some collection) and invoke
Enum.valueOf(EnumType, nameOfConstant)
But be careful because this method will throw java.lang.IllegalArgumentException
if checked enum type will not have described field.
Other way would be just iterating over collection of your enum types, getting its values (you can use Class.getEnumConstants
here) and checking if name of enum constant is same as name passed by user.
public static Enum<?> getEnumFromMany(Collection<Class<?>> enums, String value) {
for (Class<?> enumType : (Collection<Class<?>>) enums)
if (enumType.isEnum()) {
@SuppressWarnings("unchecked")
Class<Enum<?>> clazz = (Class<Enum<?>>) enumType;
for (Enum<?> en : clazz.getEnumConstants()) {
if (en.name().equals(value))
return en;
}
}
return null;
}
I used Collection> instead of Collection<Class<Enum<?>>>
because generics are not covariant so Collection<Class<Enum<?>>>
would not let you add Class<YourEnum>>
to itself.
Usage example
public enum DaysILike {
FRIDAY, SATURDAY, SUNDAY
}
public enum DaysIDontLike {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY
}
public static void main(String[] args) {
List<Class<?>> enums = new ArrayList<>();
enums.add(DaysIDontLike.class);
enums.add(DaysILike.class);
String yourString = "THURSDAY";
Enum<?> en = getEnumFromMany(enums, yourString);
System.out.println(en + " from " + en.getClass());
}
Output: THURSDAY from class SO22436944$DaysIDontLike
Upvotes: 3