Android code - the SharedPreferences class exports different methods for persisting/retrieving different preferences :
@SuppressWarnings("unchecked")
public static T retrieve(Context ctx, String key, T defaultValue) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
if (defaultValue instanceof Boolean) return (T) (Boolean) prefs
.getBoolean(key, (Boolean) defaultValue);
else if (defaultValue instanceof Float) return (T) (Float) prefs
.getFloat(key, (Float) defaultValue);
// etc - another 4 cases
}
This works and I can call boolean stored = retrieve(ctx, "BOOLEAN_KEY", true) alright - but my question is : since I already used instanceof and T has boiled down to a specific class is there a way to avoid the single and double casts and the warning : unchecked ?
EDIT : if I were to pass the class in I might as well call getBoolean() or getFloat() etc. What I want is to simplify the internals of the method and get rid of the warnings but still be able to call retrieve(ctx, "KEY", 1 or "string" or true) and get what I want back
解决方案
Well my question is was (simply) : since I already used instanceof and T has boiled down to a specific class is there a way to avoid the single and double casts and the warning : unchecked ?
And the answer is no - I am quoting this particular answer cause it shows I am not the only one who wondered. But you may wish to vote the interesting albeit a bit off topic answer by @yshavit :)