Java泛型 - 在我调用instanceof之后避免强制转换(以及未经检查的警告)的任何方式? [英] Java generics - any way to avoid casts (and unchecked warnings) after I have called instanceof?
问题描述
Android代码 - SharedPreferences类导出不同的持久化/检索不同首选项的方法:
@SuppressWarnings(unchecked)
public static< T> T检索(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 - 另外4种情况
}
调用 boolean stored = retrieve(ctx,BOOLEAN_KEY,true)
好吧 - 但我的问题是:因为我已经使用 instanceof
和 T
已经归结为一个特定的类有没有办法避免单一和双重强制转换和警告:未经检查
$ b
编辑 :如果我要传入类,我也可以调用 getBoolean()
或 getFloat()
等等我想要的是简化方法的内部并摆脱警告但仍然可以调用 retrieve(ctx,KEY,1或string或true)
并获取我想要的内容
<我的问题是(简单地说):因为我已经使用了instanceof,而T已经归结为一个特定的类是有一种方法可以避免单人和双人演员以及警告:未经检查?
答案是否 - 我引用了这个特定的答案,因为它表明我不是唯一一个想知道的人。但是,您可能希望对@yshavit的主题答案进行一些有趣的投票:)
Android code - the SharedPreferences class exports different methods for persisting/retrieving different preferences :
@SuppressWarnings("unchecked")
public static <T> 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 :)
这篇关于Java泛型 - 在我调用instanceof之后避免强制转换(以及未经检查的警告)的任何方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!