Kin*_*uoc 4 java generics android
我的android应用程序中有一个函数:
public static <T> void saveLocalData(Context context, String key, Class<T> value) {
// Check type of value here
SharedPreferences prefs = context.getSharedPreferences(
Constants.PREFERENCES_KEY, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
if(value.isAssignableFrom(String.class)){
//Put value here
}
else if(value.isAssignableFrom(Boolean.class)){
//Put value here
}
editor.commit();
}
Run Code Online (Sandbox Code Playgroud)
我想在这个函数中检查值的类型(我想检查两种类型Boolean和String),但我不知道该怎么做!任何人都可以提出任何建议吗?谢谢!
编辑:谢谢大家的帮助!我还有一个问题是如何将其保存到Preferences?
确定此Class对象表示的类或接口是否与指定的Class参数表示的类或接口相同,或者是它们的超类或超接口
更新:通过编辑问题,并在a中设置键/值SharedPreferences.Editor,使用putString()和putBoolean().
考虑到您需要接收值作为参数.请注意,如果您收到该值,则您已经可以访问其类(因此您不需要Class<T>作为参数isAssignableFrom()),并通过instanceof运算符进行检查:
public static <T> void saveLocalData(Context context, String key, T value) {
SharedPreferences prefs = context.getSharedPreferences(
Constants.PREFERENCES_KEY, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
if (value instanceof String) {
editor.putString(key, (String) value);
}
else if (value instanceof Boolean){
editor.putBoolean(key, (Boolean) value);
}
editor.commit();
}
Run Code Online (Sandbox Code Playgroud)