1

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?

3
  • 1
    "...and use it's class and name in the method using the same thing" What do you mean by this? Can you give an example of what you're trying to do? Commented May 22, 2018 at 9:53
  • I am clueless what you might mean with "do something with [...] but in a more generic way." Commented May 22, 2018 at 9:54
  • @f1sh Edited the commented portion for clarity. Please let me know if it's clear. Commented May 22, 2018 at 10:51

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.