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". It's not possible to use instanceof
, here, because you can't check the runtime type due to type-erasure.
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?
Use the following method:
Class<? extends TargetClass> narrowClass = clazz.asSubclass(TargetClass.class);
Here is a Link to the documentation.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.