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

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

    enum courseList {
        JAVA,
        C,
        PYTHON,
        PERL
    }

    enum generalInformation {
        NAME,
        AGE,         


        
相关标签:
6条回答
  • 2021-01-03 19:00

    If you want to pass a single value from the enum

        public class Test {
    
        enum GeneralInformation{
            NAME;
        }
    
        private static void print(GeneralInformation val){
            System.out.println(val);
        }
    
        public static void main(String[] args) {
            print(GeneralInformation.NAME);
        }
    }
    

    else if you want whole class to be passed then, as it was not clear from the question

    private static void print(Class<?> generalInfo){
    
        }
    
        public static void main(String[] args) {
            print(GeneralInformation.class);
        }
    
    0 讨论(0)
  • 2021-01-03 19:00

    printEnumValue(EnumValues.generalInformation.NAME,EnumValues.generalInformation.AGE,EnumValues.generalInformation.PHONE);
    Receiving:

    public static void printEnumValue(EnumValues.generalInformation en){
    System.out.println(en.toString());
    }
    
    0 讨论(0)
  • 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 <T extends Enum<T>> 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 <T extends Enum<T>> void printEnum2(Class<T> 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.

    0 讨论(0)
  • 2021-01-03 19:04

    TestEnumMain.java:

    package enumSample;
    
    import org.apache.commons.lang3.EnumUtils; 
    
        public static void main(String[] args) {
            boolean result= isValidEnum(DummyEnum.class, "APPLE"); 
            System.out.println("result= " + result); 
            boolean result2= isValidEnum2(DummyEnum.class, "COF"); 
            System.out.println("result2= " + result2); 
            //boolean result3= isValidEnum2(A_Different_Enum.class, "COF");  //works
            //System.out.println("result3= " + result3); 
    
        }
    
        public static<E extends Enum<E>> boolean isValidEnum2(Class<E> enumClass, String enumName) {
    
            System.out.println("enumClass.getEnumConstants().length= " + enumClass.getEnumConstants().length); 
            System.out.println("enumClass.getEnumConstants()[0]= " + enumClass.getEnumConstants()[0]); 
            System.out.println("enumClass.getEnumConstants()[1]= " + enumClass.getEnumConstants()[1].name()); 
            System.out.println("enumName.valueOf(enumClass)= "+ enumName.valueOf(enumClass));
    
            if(enumName== null) {
                return false; 
            } else {
                try {
                    if(enumClass.isAssignableFrom(DummyEnum.class)) { /*Checks if enumClass is an instance of DummyEnum.class*/
                        for (int i=0; i!= enumClass.getEnumConstants().length; i++) {
                            System.out.println("(DummyEnum) enumClass.getEnumConstants()["+i+"]).code()= "+ ((DummyEnum) enumClass.getEnumConstants()[i]).code());          
                            if(enumName.equals(((DummyEnum) enumClass.getEnumConstants()[i]).code())) {
                                return true; 
                            }
                        }                   
                        return false; 
                    } else {
                        Enum.valueOf(enumClass, enumName); 
                        return true; 
                    }
                } catch (IllegalArgumentException var3){
                    return false; 
                }
            }
    
        }
    
        //Original Method from apache.commons.long3.EnumUtils: 
        public static<E extends Enum<E>> boolean isValidEnum(Class<E> enumClass, String enumName) {
            if(enumName== null) {
                return false; 
            } else {
                try {
                    Enum.valueOf(enumClass, enumName); 
                    return true; 
                } catch (IllegalArgumentException var3){
                    return false; 
                }
            }
        }
    }
    

    DummyEnum.java:

    package enumSample;
    
    public enum DummyEnum {
        APPLE("APP"), 
        GOOGLE("GOOG"), 
        CAPITAL_ONE("COF");
    
        private String code; 
        DummyEnum(String code) {this.code= code;}
        public String code() {return code;}
    }
    
    0 讨论(0)
  • 2021-01-03 19:09

    An enum is used just like a type:

    static void printEnumValue(courseList generalInformation) { // how to receive enum  in this block
    

    used like:

    printEnumValue(courseList.JAVA);

    0 讨论(0)
  • 2021-01-03 19:14

    An enum is a class. So you can pass an instance of the class (EnumValues.generalInformation.PHONE for example), or you can pass the class itself (EnumValues.generalInformation.class for example).

    If you want to list all the instances of an enum class, you need to pass the enum class, and use EnumSet.allOf(EnumValues.generalInformation.class) for example.

    Your confusion principally comes from the fact that you don't respect the Java naming conventions. ENums are classes and should start with an upper-case letter (GeneralInformation for example). An other source of confusion is the bad choice of names. JAVA is not a course list. It's a course. So the enum should be named Course.

    0 讨论(0)
提交回复
热议问题