My code is as follows
package com.foo;
public class TestComposition {
public static void main(String[] args) {
try {
Class<Foo> fooClass =
(Class<Foo>) Class.forName("Foo");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
The assignment within the ‘try’ block results in a warning stating
Type safety: Unchecked cast from Class<capture#1-of ?> to
Class<Foo>
Why is this?
Well, to start with let’s be clear where the problem is – it’s in the cast itself. Here’s a shorter example:
This still has the same problem. The issue is that the cast isn’t actually going to test anything – because the cast will be effectively converted to the raw
Classtype. ForClass<T>it’s slightly more surprising because in reality the object does know the class involved, but consider a similar situation:That cast isn’t going to check that it’s really a
List<String>, because that information is lost due to type erasure.Now in your case, there’s actually a rather simpler solution – if you know the class name at compile-time anyway, just use:
If you can provide a more realistic example where that’s not the case, we can help you determine the most appropriate alternative.