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;
}
}
}
}
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;
}
}
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With