在我的代码中的很多地方,我有这样的东西:
public Class mySpecialMethod() {
return MySpecialClass.class;
}
导致警告
类是原始类型。对泛型 Class 的引用应该被参数化。
但是,如果我更换
Class
和
Class<? extends Object>
警告消失。
这种简单的做法可以吗,还是以后会造成麻烦?
It's the correct thing to do only if there really is no common base class or interface that the Class object needs to represent.
Also Class<?>
is effectively the same as Class<? extends Object>
.
根据您想要实现的目标,您可以更加精确:
public Class<MySpecialClass> mySpecialMethod() {
return MySpecialClass.class;
}
这里不是真正的 Java 程序员,但阅读了一些关于泛型的好论文。
是的,您应该添加一些通配符或确切的类型 ( Class<MySpecialClass>
) 以增加安全性。原因是 Class 是泛型的。因此,在擦除它们的泛型类型参数之后是相同的Class<Bar>
。Class<Foo>
它们都变成Class
了,所谓的原始类型。编译时会发生这种擦除。一些示例来说明这一点,其中编译器可以帮助您进行自动转换(为简洁起见,省略了异常处理):
class Mine { }
class Vara {
public static void main(String... args) {
{ // works. translated to Mine m = (Mine) c.newInstance();
Class<Mine> c = Mine.class;
Mine m = c.newInstance();
}
{ // doesn't work. need a cast: Mine m = (Mine) c.newInstance();
Class c = Mine.class; // also Class<?> or Class<? extends Object>
Object o = c.newInstance(); // but this works. pointing to a Mine
Mine m = (Mine) c.newInstance(); // needs a manual cast
}
}
}
Saying Class<?>
(and the equivalent Class<? extends Object>
), you tell the compiler you really wanted a Class whose T
is Object, and didn't accidentally used the raw type. But it won't add any convenience casts. All that generics do is to insert automatic casts for you, to cast from Object
to the destination type. Generics are the same whether used with type U or with type T at runtime for compatibility reasons with older java versions.