Class<? extends MyClass> cls = (Class<? extends MyClass>) Class.forName(className);
someMethod(cls); // someMethod expects a Class<? extends MyClass>
The above statement gives a warning "Type safety: Unchecked cast from Class<capture#5-of ?>
to Class<? extends MyClass>
".
Class<?> cls0 = Class.forName(className);
if (cls0 instanceof Class<? extends MyClass>) {
Class<? extends MyClass> cls = (Class<? extends MyClass>)cls0;
someMethod(cls);
}
This time I get an error, because of type erasure...
Class<?> cls0 = Class.forName(className);
if (MyClass.class.isAssignableFrom(cls0)) {
Class<? extends MyClass> cls = (Class<? extends MyClass>)cls0;
someMethod(cls);
}
This time I know that the cast is safe, but the compiler doesn't, and still gives the warning. (If you ask me, the compiler is being a bit thick here.)
Is there any way to avoid this warning (except for SuppressWarnings)?
The correct way to do what you want is:
Class.forName(className).asSubclass(MyClass.class);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With