I've written the class below to let me get an enumerated value out of an Android Spinner.
There are two lines in getValue() neither of which compile.
How should I do this?
public class EnumSpinnerListener implements AdapterView.OnItemSelectedListener {
private String mValue = null;
public EnumSpinnerListener(AdapterView> adapterView) {
adapterView.setOnItemSelectedListener(this);
}
@Override
public void onItemSelected(AdapterView> adapterView, View view, int i, long l) {
mValue = adapterView.getItemAtPosition(i).toString();
}
@Override
public void onNothingSelected(AdapterView> adapterView) {
// do nothing
}
public T getValue() {
return Enum.valueOf(T.class, mValue); // cannot select from a type variable
return T.valueOf(mValue); // valueOf(java.lang.Class, String) in enum cannot be applied to (java.lang.String)
}
}
解决方案
Due to type erasure, T will have no meaning at runtime, which is why the expression T.class is illegal. The workaround is to reference a Class instance:
public class EnumSpinnerListener> // note the correction here
implements AdapterView.OnItemSelectedListener {
private final Class type;
private String mValue = null;
public EnumSpinnerListener(Class type, AdapterView> adapterView) {
this.type = type;
adapterView.setOnItemSelectedListener(this);
}
public T getValue() {
return Enum.valueOf(type, mValue);
}
}