9

在我的代码中的很多地方,我有这样的东西:

public Class mySpecialMethod() {
  return MySpecialClass.class;
}

导致警告

类是原始类型。对泛型 Class 的引用应该被参数化。

但是,如果我更换

Class

Class<? extends Object>

警告消失。

这种简单的做法可以吗,还是以后会造成麻烦?

4

4 回答 4

15

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>.

于 2008-12-16T08:08:56.580 回答
6

是的,完全正确。

您需要指定类型。如果不能,则必须指定通配符。

进一步阅读:Java 语言规范:参数化类型

于 2008-12-16T07:05:19.657 回答
6

根据您想要实现的目标,您可以更加精确:

public Class<MySpecialClass> mySpecialMethod() {
  return MySpecialClass.class;
}
于 2008-12-16T07:47:26.670 回答
4

这里不是真正的 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.

于 2008-12-16T08:05:53.903 回答