我试图将枚举的保存概括为首选项。
要保存枚举,我可以使用:
public static <T extends Enum<T>> void savePreference(final Context context, final String id, final T value) {
SharedPreferences settings = context.getSharedPreferences(SESSION_TOKEN, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(id, value.name());
editor.apply();
}
我正在尝试执行以下操作,这将允许我将首选项读入通用枚举:
public static <T extends Enum<T>> T getPreference(final Context context, final String id, final T defaultValue) {
try {
SharedPreferences settings = context.getSharedPreferences(SESSION_TOKEN, Context.MODE_PRIVATE);
String name = settings.getString(id, null);
return name != null ? Enum.valueOf(T, name) : defaultValue;
} catch (Exception e) {
Log.e("ERROR GETTING", e.toString());
return defaultValue;
}
}
但这给了我一个错误:
Error:(93, 48) error: cannot find symbol variable T
在“enum.valueof(t,name)”表达式中。
我也尝试过使用
T.valueOf(name)
但这会产生参数不匹配错误。我可以通过不使用泛型和编码特定的实现来解决这个问题,但这有点违背了目的:
public static Constants.ButtonLocations getPreference(final Context context, final String id, final Constants.ButtonLocations defaultValue) {
try {
SharedPreferences settings = context.getSharedPreferences(SESSION_TOKEN, Context.MODE_PRIVATE);
String name = settings.getString(id, null);
return name != null ? Constants.ButtonLocations.valueOf(name) : defaultValue;
} catch (Exception e) {
Log.e("ERROR GETTING", e.toString());
return defaultValue;
}
}
如何创建getPreference的通用版本?
最佳答案
您可以将Class<T>
参数添加到方法中
public static <T extends Enum<T>> T getPreference(final Context context, final String id, final Class<T> clazz, final T defaultValue)
那你就可以用
Enum.valueOf(clazz, name)
或者,如果
defaultValue
永远不会是null
,那么可以去掉这个额外的参数并使用这个默认值来获取类。Enum.valueOf(defaultValue.getDeclaringClass(), name)