I've got a class that I'd like to use a generic enum type in, like this:
public class PageField<E extends Enum<E>>{
}
It seems like I should be able to have a getter method inside that class that then could return an enum <E> instance, like this:
public E getSelectedValue() {
String value = getValueFromElement(this.id);
return E.valueOf(value);
}
But i keep getting the following error:
Inferred type 'java.lang.Object' for type parameter 'T' is not within its bound; should extend 'java.lang.Enum'
What am I doing wrong? Is this possible?
You cannot call the method valueOf on E: it is not an object, it is just a type parameter.
What you should do is pass the Class of the current enum type parameter so that you can use it to retrieve the enum value:
public class PageField<E extends Enum<E>>{
private Class<E> enumClass;
public PageField(Class<E> enumClass) {
this.enumClass = enumClass;
}
public E getSelectedValue() {
String value = getValueFromElement(this.id);
return Enum.valueOf(enumClass, value);
}
}
Unfortunately, there is no way to retrieve the class of the type E because of type erasure, so you need to give it explicitely.
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