Home > Net >  How to avoid type safety warning with generic interfaces and Class.forName
How to avoid type safety warning with generic interfaces and Class.forName

Time:09-10

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?

CodePudding user response:

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);
    ...
}

CodePudding user response:

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).

  • Related