【发布时间】:2011-04-12 23:59:36
【问题描述】:
我正在尝试使用一种最简单的反射形式来创建类的实例:
package some.common.prefix;
public interface My {
void configure(...);
void process(...);
}
public class MyExample implements My {
... // proper implementation
}
String myClassName = "MyExample"; // read from an external file in reality
Class<? extends My> myClass =
(Class<? extends My>) Class.forName("some.common.prefix." + myClassName);
My my = myClass.newInstance();
对我们从 Class.forName 获得的未知 Class 对象进行类型转换会产生警告:
类型安全:从 Class到 Class
我尝试过使用instanceof检查方法:
Class<?> loadedClass = Class.forName("some.common.prefix." + myClassName);
if (myClass instanceof Class<? extends RST>) {
Class<? extends My> myClass = (Class<? extends My>) loadedClass;
My my = myClass.newInstance();
} else {
throw ... // some awful exception
}
但这会产生编译错误:
Cannot perform instanceof check against parameterized type Class<? extends My>. Use the form Class<?> instead since further generic type information will be erased at runtime. 所以我想我不能使用instanceof 方法。
我该如何摆脱它,我应该如何正确地做到这一点?是否可以在没有这些警告的情况下使用反射(即不忽略或抑制它们)?
【问题讨论】:
-
不确定强类型在这里为您带来了什么。当您执行 Class.forName 时,编译时无法保证生成的类的类型。无论如何,您都需要转换为 (My)。打字为您带来了哪些额外的编译时安全性?
-
我只是在玩好东西,并且急切地想知道 Sun 的建筑师在设计这个警告时抽了什么样的锅。看来终于有答案了。
标签: java reflection compiler-warnings type-safety