Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create generic enum converter?

I want to write a generic class that can be used like new EnumConverter(MyEnum.class);

But hwo to I have to write that class so that it works with generic calls to enum.values()?

public class EnumConverter {
    public EnumConverter(Class<Enum<?>> type) {
        this.type = type;
    }

    public EnumConverter convert(String text) {
        //error: Type mismatch: cannot convert from element type capture#1-of ? to Enum<?>
        for (Enum<?> candidate : type.getDeclaringClass().getEnumConstants()) {
            if (candidate.name().equalsIgnoreCase(text)) {
                return candidate;
            }
        }
    }
}
like image 341
membersound Avatar asked Sep 08 '25 08:09

membersound


2 Answers

Your return type of method convert is wrong: Shoud be Enum instead of EnumConverter. And then you don't have to call getDeclaringClass() but use the Class you already have in type.

I would suggest an even more generic approach:

public static class EnumConverter<T extends Enum<T>>
{

    Class<T> type;

    public EnumConverter(Class<T> type)
    {
        this.type = type;
    }

    public Enum<T> convert(String text)
    {
        for (Enum<T> candidate : type.getEnumConstants()) {
            if (candidate.name().equalsIgnoreCase(text)) {
                return candidate;
            }
        }

        return null;
    }
}
like image 163
flo Avatar answered Sep 09 '25 20:09

flo


your question is inconsistent and not valid code: 1) this.type is not defined as a field 2) you define convert to return EnumConverter but return an Enum

to return a enum value of an enum from text you do not need generic stuff. you simply use:

Enum.valueOf(MyEnum.class, "TWO")
like image 27
lumo Avatar answered Sep 09 '25 21:09

lumo