Itโs good to start by making it clear where the problem is in the act itself. Here is a shorter example:
public class Test { public static void main(String[] args) throws Exception { Object x = (Class<Test>) Class.forName("Test"); } }
This problem still has the same problem. The problem is that the actor is not actually going to test anything, because the cast will be effectively converted to the raw Class type. For Class<T> this is somewhat more surprising, because the object actually knows the class, but consider a similar situation:
List<?> list = ... get list from somewhere; List<String> stringList = (List<String>) list;
This will not check if this is a List<String> , because this information is lost due to type erasure.
Now in your case there is actually a fairly simple solution - if you know the class name at compile time, just use:
Class<Foo> fooClass = Foo.class;
If you can provide a more realistic example where this is not the case, we can help you determine the most suitable alternative.
source share