How to throw objects like java.lang.Class <?> Without warnings?

I have a 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 gives me an “unchecked throw” warning, perhaps because the check is isAssignableFromnot considered a “check”. It is impossible to use instanceofhere because you cannot check the execution type due to type erasure.

Is there a way to write this code without warning the compiler? Or is this the only way to get rid of the warning in order to add a method @SupprssWarnings("unckeched")to a method?

+4
source share
1 answer

Use the following method:

 Class<? extends TargetClass> narrowClass = clazz.asSubclass(TargetClass.class);

Here is the link in the documentation.

+5
source

Source: https://habr.com/ru/post/1695766/


All Articles