Reputation: 935
I have few enums like the following:
public enum Season {
SPRING, SUMMER, AUTUM, WINTER
}
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
I am trying to write a common method for a concern.
private void doSomethingWithAnyEnum(Class enumClass,String checkThisProperty)
{
if(EnumUtils.isValidEnum(enumClass, checkThisProperty))
{
//here i should be able to call valueOf(String) method on enum
//without bothering about the type coming in.
}
}
So that I can call this method like:
doSomethingWithAnyEnum(Days.class,"blah") ;
doSomethingWithAnyEnum(Seasons.class,"blah");
I am stuck on how to pass a enum and use it's class and name in the method using the same thing. I tried using simpleName()
but it doesn't do the job here. Is there a way to do this?
Upvotes: 1
Views: 687
Reputation: 44240
EnumUtils
from Apache Commons already has a method to do this: getEnum
. As you're already using it for isValidEnum
, it makes sense to use it for this as well.
Your method signature should also use generics rather than raw types to enforce at compile-time that doSomethingWithAnyEnum
is called with an enum and not any old class. I have fixed that for you as well.
private <E extends Enum<E>> void doSomethingWithAnyEnum(Class<E> enumClass,
String checkThisProperty)
{
if (EnumUtils.isValidEnum(enumClass, checkThisProperty))
{
final E value = EnumUtils.getEnum(enumClass, checkThisProperty);
System.out.println(value.name()); //or whatever else you want to do
}
}
Without this change to the method signature, I could call this method with
doSomethingWithAnyEnum(String.class, "hello")
and it would only fail at runtime. It's better to do the check at compile-time.
Upvotes: 2
Reputation: 18235
You may want to modify your function like this:
public <T extends Enum<T>> void doSomethingWithAnyEnum(Class<T> tClass, String name) {
T t = Enum.valueOf(tClass, name);
}
Your original method took a random Class enumClass
class type, which accept any class. It will throw runtime exceptions when treat input class as enum
Upvotes: 2