Reputation: 6656
I have the following code which is forking fine:
private <X extends SomeInterface<MyImplementation>> void test(String fqcn)
{
Class<X> c = (Class<X>)Class.forName(fqcn).asSubclass(SomeInterface.class);
...
}
However, I get a type safety warning
Type safety: Unchecked cast from Class<capture#2-of ? extends SomeInterface> to Class<X>
and wondering how to fix it?
Upvotes: 0
Views: 130
Reputation: 320
Read the reflection java.lang.Class "api docs" for forName method, it should be wrapped in java.lang.ClassNotFoundException and java.lang.ClassCastException. The correct Exception(s) should remove that warning.
use isInstance(theCreatedClassReference) from java.lang.Class
don't want to try without code and compiler , take too long for me.
isInstance() returns a boolean and is the correct to use for Class.forName(stringnametoload) check alike the instanceof operator when creating a Class check its constructed reference in an if test the multi argument Class.forName allows class loading usage designation of whether it is "initialized".
sorry about the botched code attempt.
If you are actually making a usable reference then maybe check with instanceof but the actions DO require the exception wrappers (not a bad idea when they can be interfaces and other types in one).
I can only presume from your code you are loading a class that will be returned "something like (and as the byte code compiler sees it)" a <T> type by genericsthat could be any type, so the runtime would have no idea what resource of byte code would be loaded. Not knowing what the T type will be is extremely dangerous. If you flag Class.forName with initialize false using its multi argument method version you can load an uninstantiated class as a test to see that the dynamic resource is true for the compiled code before it is able to be loaded live. It would then tested the resource class loaded.
Upvotes: 0
Reputation: 28988
There is no way to prove that this casting is safe and would succeed. You're performing casting of Class<?>
(of unknown type) returned by Class.forName()
into the Class<X>
(of something), the compiler can't verify if what you're doing is correct.
The only thing you can do is to suppress the warning by placing annotation @SuppressWarnings("unchecked")
on the method on the problematic statement:
@SuppressWarnings("unchecked")
private <X extends SomeInterface<MyImplementation>> void test(String fqcn) {
Class<X> c = (Class<X>)Class.forName(fqcn).asSubclass(SomeInterface.class);
...
}
Or
private <X extends SomeInterface<MyImplementation>> void test(String fqcn) {
@SuppressWarnings("unchecked")
Class<X> c = (Class<X>)Class.forName(fqcn).asSubclass(SomeInterface.class);
...
}
Upvotes: 2