Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't access Enum<?>.valueOf(String) method for generic type (or how to get .class of generic argument)?

Tags:

java

generics

How can I access static method of the enum if given enum is a parameter of generic class?

Consider following example

public class EnumListBox<T extends Enum<T>> extends ListBox implements LeafValueEditor<T>
{
    @Override
    public void setValue(T value)
    {
        // something..
    }

    @Override
    public T getValue()
    {
        int ndx = getSelectedIndex();
        String val = getValue(ndx);
        return T.valueOf(val);
    }
}

For some reason Enum<?>.valueOf(String) is not available to me. Another version of this method has two parameters and wants Class<Enum<?>> which I can't instantiate as T.class.

How would you fix this? Basically I want to have universal ListBox wrapper for any enum.

like image 711
expert Avatar asked Feb 29 '12 01:02

expert


1 Answers

The easiest fix is to pass an instance of the enum class in the constructor for EnumListBox.

public class EnumListBox<T extends Enum<?>> extends ListBox implements LeafValueEditor<T>
{
    private final Class<T> mClazz;

    public EnumListBox(Class<T> clazz) {
        mClazz = clazz;
    }

    @Override
    public T getValue()
    {
        int ndx = getSelectedIndex();
        String val = getValue(ndx);
        return Enum.valueOf(mClazz, val);
    }
}
like image 169
Ted Hopp Avatar answered Oct 03 '22 07:10

Ted Hopp