I am trying to use one of the simplest forms of reflection to instantiate a class:
package some.common.prefix;
public interface My {
void configure(...);
void process(...);
}
public class MyExample implements My {
...
}
String myClassName = "MyExample";
Class<? extends My> myClass =
(Class<? extends My>) Class.forName("some.common.prefix." + myClassName);
My my = myClass.newInstance();
Specifying an unknown class object obtained from Class.forNamegives a warning:
Type safety: Unchecked cast from Class <capture # 1-of?> To Class <? extends My>
I tried using the instanceofcheck approach :
Class<?> loadedClass = Class.forName("some.common.prefix." + myClassName);
if (myClass instanceof Class<? extends RST>) {
Class<? extends My> myClass = (Class<? extends My>) loadedClass;
My my = myClass.newInstance();
} else {
throw ...
}
but this leads to a compilation error:
Cannot perform instanceof check against parameterized type Class<? extends My>. Use the form Class<?> instead since further generic type information will be erased at runtime.So, I can not use the approach instanceof.
How do I get rid of it and how should I do it right? Can reflection be used without these warnings (i.e., do not ignore or suppress them)?