user2250246
user2250246

Reputation: 3967

Handling several enum-types in a generic way

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?

Upvotes: 1

Views: 76

Answers (1)

Andreas
Andreas

Reputation: 159096

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);
}

Upvotes: 2

Related Questions