My code is as follows
package com.foo;
public class TestComposition {
public static void main(String[] args) {
try {
Class
Well, to start with let's be clear where the problem is - it's in the cast itself. Here's a shorter example:
public class Test {
public static void main(String[] args) throws Exception {
Object x = (Class) Class.forName("Test");
}
}
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 Class
type. For Class
it's slightly more surprising because in reality the object does know the class involved, but consider a similar situation:
List> list = ... get list from somewhere;
List stringList = (List) list;
That cast isn't going to check that it's really a List
, 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:
Class fooClass = Foo.class;
If you can provide a more realistic example where that's not the case, we can help you determine the most appropriate alternative.