简体   繁体   中英

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

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.

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);
    }
}

Use of reflection tends to be a bad idea. Unfortunately there is no non-reflection meta enum type in Java. In this case we just need the list of actual values.

public class EnumListBox<T extends Enum<T>> extends ListBox implements LeafValueEditor<T> {
    private final List<T> values;

    public EnumListBox(T[] values) {
        return Collections.unmodifiableList(Arrays.asList(values.clone()));
    }

    @Override public void setValue(T value) {
        // something..
    }

    @Override public T getValue() {
        int index = getSelectedIndex();
        return values.get(index);
    }
}

Construct as new EnumListBox<>(MyEnum.values()) . You don't really have to tie the class to enums.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM