Search code examples
javamethodsinputenumsany

Pass in Any Enum into Method


I am writing in Java and trying to create a method that will take any Enum class that I pass to it, as described here (mostly): Java: Generic method for Enums

I am getting a problem when I try to pass an enum into this type of method. It wants me to change the method to take a specific Enum class. Does anyone know what I am doing wrong?

Here is my version of the method:

public Class Presenter{
public static <E extends Enum<E>> List<String> getEnumString(Class<E> eClass){
    List<String> returnList = new ArrayList<String>();

    for (E en: EnumSet.allOf(eClass)){
        returnList.add(en.name());
}
    return returnList;
}
}

and here is what I am attempting to pass in. The error is saying that the argument is not applicable, and it suggests changing the method above to only take MyEnumClass:

MyEnumClass eclass;

List<STtring> string = presenter.getEnumString(eclass);

I thank anyone who can help in advance.

Thanks!


Solution

  • MyEnumClass eclass;
    

    eClass is a reference to a MyEnumClass object. What you need to pass into your function is the class type itself. The syntax is:

    MyEnumClass.class
    

    The following code will do what you want. Notice I pass in MyEnumClass.class, not a variable.

    import java.util.ArrayList;
    import java.util.EnumSet;
    import java.util.List;
    
    public enum MyEnumClass
    {
        ENUM_1, ENUM_2, ENUM_3, ENUM_4, ENUM_5;
    
        public static void main(String[] args)
        {
            for (String string : getEnumString(MyEnumClass.class))
                System.out.println(string);
        }
    
        public static <E extends Enum<E>> List<String>
                getEnumString(Class<E> eClass)
        {
            List<String> returnList = new ArrayList<String>();
    
            for (E en : EnumSet.allOf(eClass))
            {
                returnList.add(en.name());
            }
    
            return returnList;
        }
    }
    

    Output:

    ENUM_1
    ENUM_2
    ENUM_3
    ENUM_4
    ENUM_5