问题
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<T extends Enum> 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<T>, String) in enum cannot be applied to (java.lang.String)
}
}
回答1:
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<T>
instance:
public class EnumSpinnerListener<T extends Enum<T>> // note the correction here
implements AdapterView.OnItemSelectedListener {
private final Class<T> type;
private String mValue = null;
public EnumSpinnerListener(Class<T> type, AdapterView<?> adapterView) {
this.type = type;
adapterView.setOnItemSelectedListener(this);
}
public T getValue() {
return Enum.valueOf(type, mValue);
}
}
来源:https://stackoverflow.com/questions/17784067/getting-an-enumerated-value-out-of-an-android-spinner