Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return an enum from a class using generic enum type in Java

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?

like image 634
LimaNightHawk Avatar asked Oct 26 '25 08:10

LimaNightHawk


1 Answers

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.

like image 109
Tunaki Avatar answered Oct 27 '25 23:10

Tunaki