[英]How to cast objects of type java.lang.Class<?> without warnings?
I've got some code that looks like this: 我有一些看起来像这样的代码:
Class<?> clazz = Class.forName(someClassName);
if(TargetClass.class.isAssignableFrom(clazz))
{
Class<? extends TargetClass> narrowClass = (Class<? extends TargetClass>)clazz;
// Use the narrowClass for stuff
}
This code give me an "unchecked cast" warning, probably because the isAssignableFrom
check doesn't count as a "check". 这段代码给了我一个“未经检查的强制转换”警告,可能是因为isAssignableFrom
检查不算作“检查”。 It's not possible to use instanceof
, here, because you can't check the runtime type due to type-erasure. 这里不可能使用instanceof
,因为由于类型擦除而无法检查运行时类型。
Is there any way to write this code without a compiler warning? 有没有办法在没有编译器警告的情况下编写此代码? Or is the only way to get rid of the warning to add @SupprssWarnings("unckeched")
to the method? 或者是摆脱警告的唯一方法是将@SupprssWarnings("unckeched")
到方法中?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.