I am loading a class using classloader which returns me Class<?> and now I want to pass the class to another method or function that takes Class<? extends SomeClass>.
Now when I try to cast:
Class<?> clazzFromClassLoader = Class.forName(nameOfClass);
Class<? extends Someclass> clazz = (Class<? extends SomeClass>)clazzFromClassLoader;
//second line gives unchecked cast warning
I can make sure that there is no class cast exception by using
SomeClass.isAssignableFrom(clazzFromClassLoader);
But is there a way to get rid of unchecked cast?
Yes: you can write:
(See
asSubclass‘s Javadoc for more information.)