简体   繁体   中英

Java enum.valueOf(String) and enum.class

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM