I have a function in my android application:
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();
}
I want to check type of value in this function (I want to check two type Boolean and String), but I don’t know how to do it! Can anyone give any suggestion? Thanks!
Edited: Thanks every for help! I have one more problem that is how to save it value to Preferences?
You could use
Class.isAssignableFrom().UPDATE: By the edit in the question, and in order to set the key/value in a
SharedPreferences.Editor, useputString()andputBoolean().Take into account you’ll need to receive the value as an argument. Notice that if you receive the value, you can already access its class (so you don’t need
Class<T>as an argument norisAssignableFrom()), and check it by means of theinstanceofoperator: