1

So I have a java class with multiple Enums

public class Enumerations {
    public enum Days {
        Monday("MON")
        Tuesday("Tue")

        string value;
        private Days(String value){
            this.value = value
        }
        public string getValue(){
            return this.value;
        }
    }
    public enum Months{
        January("JAN")
        APRIL("APR")

        string value;
        private Months(String value){
            this.value = value
        }
        public string getValue(){
            return this.value;
        }
    }
}

And now I have another class in which I want to access the enum class via a string as i cannot instantiate the enum directly as i am unaware of the enum that is to be used and access enum values from a variable string(unaware of this as well).

class EnumParser{
    public static void main(String args[]){
        String enum = "Days";     //Will get this value from external source so its variable(Can be months or days)
        String value = "Monday"   //This is going to variable as well with value unknown.
    }
}

So how do i get output as "MON" here using string variables

Enumerations.{{Days}}.{{Monday}}.getValue();

edited the question for a clearer view, both Days ans Monday are variables.

3
  • 3
    Your problem statement is not clear. Commented Feb 14, 2019 at 5:13
  • possible is: Days.valueOf("Monday").getValue(); (solves 1/2 of your question) Commented Feb 14, 2019 at 5:16
  • @RavindraRanwala Enum name and enum value are variables(not pre defined) hence need a java statement to get output using the string variables for enum name and enum value Commented Feb 14, 2019 at 5:33

3 Answers 3

1

You can use if-else or switch statements to determine which enum to use, and then use valueOf():

String e = "Days";
String value = "Monday";

if (e.equalsIgnoreCase(Enumerations.Days.class.getSimpleName())) {
    System.out.println(Enumerations.Days.valueOf(value).getValue());
} else if (e.equalsIgnoreCase(Enumerations.Months.class.getSimpleName())) {
    System.out.println(Enumerations.Months.valueOf(value).getValue());
} else {
    System.out.println("Could not find enum");
}

Output:

MON

Update based on comment that you might have 200+ enums:

You can use reflection like so:

String e = "Days";
String value = "Monday";

String res = Arrays.stream(Enumerations.class.getDeclaredClasses())
        .filter(c -> c.getSimpleName().equalsIgnoreCase(e))
        .findFirst()
        .map(c -> {
            String result = null;
            try {
                Object o = c.getMethod("valueOf", String.class).invoke(null, value);
                result = (String) o.getClass().getMethod("getValue").invoke(o);
            } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e1) {
                e1.printStackTrace();
            }
            return result;
        }).orElse("Could not find");
System.out.println(res); //prints MON
Sign up to request clarification or add additional context in comments.

1 Comment

But what if I have 200+ enums. any other solution instead of switch case, in which I'll be able to use the enum directly
0

Make a static method which retrieves the appropriate enum value for you:

//inside Days, skips some excess array creation
private static final Days[] VALUES = Days.values();

public static Days getDay(String day) {
    return Arrays.stream(VALUES)
        .filter(d -> d.value.equalsIgnoreCase(day))
        .findAny(); //Optional<Days>
        //can use #orElse/#orElseThrow to decide behavior for a mismatch
}

Then it's a matter of simply getting the enum directly:

Days monday = Days.getDay("MON");

You can make multiple methods which filter around these inputs, if you like. Even further if you really want to get crazy, you can pass a Predicate<Days> (or whichever enum) and filter that way:

public static Days getDay(Predicate<Days> filter) {
    return Arrays.stream(VALUES)
        .filter(filter)
        //In this case I'm returning null for no match
        .findAny().orElse(null);
}

Then:

Days monday = Days.getDay(d -> d.getValue().equalsIgnoreCase("MON"));

Now in the strict case of Monday, you can use Days#valueOf, but this will throw an error if there is no enum constant for the string you search for.

Days monday = Days.valueOf("Monday"); //okay
//all of these below would throw an error
monday = Days.valueOf("monday");
monday = Days.valueOf("MONDAY");
monday = Days.valueOf("not even close to monday");

I would also adhere to conventions for enums here (all caps letters and underscores for spacing, so MONDAY).

Lastly, if this isn't just an example problem and you're actually working with days/calendar variables etc, you have the DayOfWeek and Month enums already available in the default jdk.

Comments

0

Try reflection way;

package com.company;

import java.lang.reflect.Method;

class Enumerations {
    public enum Days {
        Monday("MON"),
        Tuesday("Tue");

        String value;
        Days(String value){
            this.value = value;
        }
        public String getValue(){
            return this.value;
        }
    }
    public enum Months{
        January("JAN"),
        APRIL("APR");

        String value;
        Months(String value){
            this.value = value;
        }
        public String getValue(){
            return this.value;
        }
        }
}
public class Main {

    public static void main(String[] args) throws Exception {
        // know the specific class name
        System.out.println(Enumerations.Months.class);
        String enumName = "Days";
        String value = "Monday";
        // get the class by class name
        Class c = Class.forName("com.company.Enumerations$" + enumName);
        // new the object by value
        Object o = Enum.valueOf(c, value);
        // get the method by name
        Method method = c.getMethod("getValue");
        // invoke the method
        System.out.println(method.invoke(o));
    }
}

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.