[英]Recovering lost types while avoiding 'unchecked cast' warning
I have an object where the type of generic T
is lost at some point through a giant interface chain.我有一个对象,其中泛型
T
的类型在某个时候通过一个巨大的接口链丢失了。 I was wondering if it is possible to use a function to regain some type safety by checking the types:我想知道是否可以使用函数通过检查类型来重新获得某种类型的安全性:
private T metaData; // type of T is lost
public <R> R getMetaData(Class<R> className) {
assert className.isInstance(metaData);
return (R) metaData;
}
However, this implementation produces an "Unchecked cast: 'T' to 'R'" warning.但是,此实现会产生“未经检查的强制转换:'T' to 'R'”警告。 Is there an implementation that avoids this warning, or is the only solution to suppress it?
是否有避免此警告的实现,或者是抑制它的唯一解决方案?
You don't have to cast to R
with ()
, you could use the Class
directly instead.您不必使用
()
强制转换为R
,您可以直接使用Class
代替。 Like,喜欢,
return className.cast(metaData);
which doesn't cause any warnings here.这不会在此处引起任何警告。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.