1

I have a couple of enums which I want to make available to a web-API like

/get/enum-values?type=<enum-Name>

Enums are as follows:

public enum Color {RED, GREEN, BLUE};
public enum Status {OPEN, DONE, CLOSED};
public enum Type {CAR, BIKE, ON_FOOT};

And the code I want to write for generically handling all of these enums in the web-API is as follows:

Class<?>[] enumsArray = new Class<?>[] {
    Color.class, Status.class, Type.class
};
List<String> getValuesForEnum(String enumName) {
    List<String> returnValue = new ArrayList<>();
    // Loop over the above array to find enum corresponding to the argument
    for (Object e: foundEnum.values()) {
        returnValue.add(e.toString());
    }
    return returnValue;
}

The above function does not compile because I am not able to treat the enums generically. Is there any way to make this work?

I do not want to fallback on treating each enum independently.

Perhaps I can extend all the enums from some common enum?

3
  • Can you provide a sample input and the expected output? Commented Dec 4, 2015 at 6:10
  • Sample input to getValuesForEnum() could be "Color" and expected output is array-list of {"RED", "GREEN", "BLUE"} Commented Dec 4, 2015 at 6:14
  • In that case you might want to use a Map<String, List<Enum<?>>> (or maybe Map<String, List<String>> instead of just a List Commented Dec 4, 2015 at 6:27

1 Answer 1

2

Since there are problems with arrays of generics (compile error: "Cannot create a generic array"), it's better to use Arrays.asList():

private static final List<Class<? extends Enum<?>>> ENUMS = Arrays.asList(
        Color.class, Status.class, Type.class
);
private static List<String> getValuesForEnum(String enumName) {
    for (Class<? extends Enum<?>> enumClass : ENUMS)
        if (enumClass.getSimpleName().equals(enumName)) {
            List<String> values = new ArrayList<>();
            for (Enum<?> enumConstant : enumClass.getEnumConstants())
                values.add(enumConstant.name()); // or enumConstant.toString()
            return values;
        }
    throw new IllegalArgumentException("Unknown enum: " + enumName);
}
Sign up to request clarification or add additional context in comments.

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.