Getting rid of the uncontrolled actor in reflection
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 do:
Class<?> clazzFromClassLoader = Class.forName(nameOfClass);
Class<? extends Someclass> clazz = (Class<? extends SomeClass>)clazzFromClassLoader;
//second line gives unchecked cast warning
I can make sure there is no class exception thrown by using
SomeClass.isAssignableFrom(clazzFromClassLoader);
But is there a way to get rid of the unverified actor?
+3
source to share
1 answer
Yes: you can write:
Class<? extends Someclass> clazz =
clazzFromClassLoader.asSubclass(Someclass.class);
(See the asSubclass
Javadoc for details .)
+8
source to share