java强制转换后调用方法,Java泛型 - 在我调用instanceof之后避免强制转换(以及未经检查的警告)的任何方式?...

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 :)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值