调用“ Class.forName”时未选中的投射警告 [英] Unchecked Cast Warning when calling 'Class.forName'
问题描述
我的代码如下
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>
这是为什么?
推荐答案
首先,让我们弄清楚问题出在哪里-它在演员表中。这是一个简短的示例:
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<Test>) Class.forName("Test");
}
}
这仍然有相同的问题。问题在于强制类型转换实际上不会进行任何测试-因为强制类型转换将有效地转换为原始的 Class
类型。对于 Class< T>
来说,这有点令人惊讶,因为实际上对象确实知道所涉及的类,但是要考虑类似的情况:
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<T>
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<String> stringList = (List<String>) list;
该演员表不会检查它是否真的是 c $ c> List< String> ,因为该信息由于类型擦除而丢失。
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:
Class<Foo> 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.
这篇关于调用“ Class.forName”时未选中的投射警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!