How to pass enum as an argument in a method in java?

后端 未结 6 1143
走了就别回头了
走了就别回头了 2021-01-03 18:47
public class Enumvalues{

    enum courseList {
        JAVA,
        C,
        PYTHON,
        PERL
    }

    enum generalInformation {
        NAME,
        AGE,         


        
6条回答
  •  情深已故
    2021-01-03 19:04

    Note that your question has mixed up two different problems: Passing an Enum to a function OR Passing an Enum constant to a function. My understanding was that you want to pass the enum itself, not one of it's constants to the function. If not: refer to Narendra Pathai's answer on how to pass a single enum constant to a function. If you don't know what the difference between an enum and an enum constant is, review the docs about enums...

    I Understand that what you want is to have a print (or any other) function where you can pass any possible enum, to print each of the enum's possible values (i.e. constants). I've found the following two approaches to do this:

    Lets say we have the following enum:

    // The test enum, any other will work too
    public static enum ETest
    {
        PRINT,MY,VALUES
    }
    

    Variante 1: Pass the array of constants from your enum to your function; As the enum's constants are static values, they can easily be accessed and passed to your 'print' function as follows:

    public static void main(String[] args)
    {
        // retreive all constants of your enum by YourEnum.values()
        // then pass them to your function
        printEnum(ETest.values());
    }
    
    // print function: type safe for Enum values
    public static > void printEnum(T[] aValues)
    {
        System.out.println(java.util.Arrays.asList(aValues));
    }
    

    Variante 2: Pass the enum's class as function parameter. This might look more beautiful, but be aware that reflection is involved (performance):

    public static void main(String[] args)
    {
        printEnum2(ETest.class);
    }
    
    // print function: accepts enum class and prints all constants
    public static > void printEnum2(Class aEnum)
    {
        // retreive all constants of your enum (reflection!!)
        System.out.println(java.util.Arrays.asList(aEnum.getEnumConstants()));
    }
    

    In my opinion, it's better to use variante 1 because of the overuse of reflection in variante 2. The only advantage that variante 2 gives you, is that you have the Class object of the Enum itself (the static enum, not only it's constants) inside your function, so I've mentioned it for completeness.

提交回复
热议问题