Unchecked Cast Warning when calling 'Class.forName'

前端 未结 4 592
天命终不由人
天命终不由人 2021-01-02 16:52

My code is as follows

package com.foo;

public class TestComposition {
    public static void main(String[] args) {
        try {
            Class

        
4条回答
  •  生来不讨喜
    2021-01-02 17:32

    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.

提交回复
热议问题