Reputation: 1044
I have a lot of enum.
I would like to add a generic method for all enums allowing to find the enum by the value. Just with something like that :
public static T getEnumFromVal(String val) {
for (T e : values()) {
if (e.getVal().equals(val)) {
return e;
}
}
return null;
}
I could make the enum implements an interface, but unfortunately I am using Java 6 and I can not declare a static method :( ...
Do you have an other idea ?
Upvotes: 0
Views: 202
Reputation: 1117
This method already exists in the Java API:
Enum.valueOf(Type.class, "Enum String");
This method also exists on all enum types, for example if you have an Enum called Color
:
Color.valueOf("RED");
will return the enum type Color.RED
.
Upvotes: 8
Reputation: 691755
public static <T extends Enum<T> & HasVal> getEnumFromVal(Class<T> enumClass, String val) {
for (T e : enumClass.getEnumConstants()) {
if (e.getVal().equals(val)) {
return e;
}
}
return null;
}
where HasVal
is the common interface defining the getVal()
method
Upvotes: 2