以下代码使用Reflection API检索字段的值。 正如您在提供的图像中看到的,这会生成未选中的强制转换警告。 可以使用 @SuppressWarnings("未选中")来抑制警告。我想知道是否有替代品呢?
更新:KeyType是通用的。所以 KeyType.class.cast(object); 由于类型擦除而无法工作。
private K getId(Field idField, V o) {
K id = null;
try {
idField.setAccessible(true);
id = (K) idField.get(o);
} catch (IllegalAccessException ignored) {
/* This never occurs since we have set the field accessible */
}
return id;
}
解决方案: 似乎 SuppressWarnings 注释就是这里的方式..感谢您的时间。
答案 0 :(得分:2)
Class方法强制转换并不需要@SupressWarnigns,即使它仍然可以抛出ClassCastException。
KeyType keyType = KeyType.class.cast( idField.get(o) );
你可以 - 因为在那个位置你应该知道通用参数 - 继续这样:
private static class ListInteger extends ArrayList<Integer>{}
Object obj = new ArrayList<Integer>();
ListInteger test = ListInteger.class.cast(obj);
一旦你有了KeyType类的对象,你当然可以
KeyType keyTypeX = ...; // not null
KeyType keyType = keyTypeX.getClass().cast( obj );
还有其他选择,虽然@SuppressWarnings不是很糟糕 - 尝试将其限制为声明+作业,不要把它放在方法上。
答案 1 :(得分:1)
Field get
方法的签名是
public Object get(Object obj) {
...
}
由于它不是通用的,因此返回类型为Object,您无法强制执行任何错误以显示在编译时。
如果您确定值的类型始终为ValueType
,则向该方法添加文档,说明类型将始终为ValueType并使用@SuppressWarnings(&#34;未选中&#34; )。