相关疑难解决方法(0)

什么是原始类型,为什么我们不应该使用它?

问题:

  • 什么是Java中的原始类型,为什么我经常听说不应该在新代码中使用它们?
  • 如果我们不能使用原始类型,它有什么替代方案,它是如何更好的?

java generics raw-types

617
推荐指数
13
解决办法
20万
查看次数

在原始类类型上忽略显式方法类型参数;编译器错误?

我在调用具有显式类型参数的泛型方法时遇到编译器错误,就好像未考虑显式类型参数一样。最小的例子:

class CastExample {
    static class ThingProducer<S> {
        public <T> T getThing() { return null; }
    }

    static class ThingA {}

    public static void main(String... args) {
        ThingProducer thingProducer = new ThingProducer();
        ThingA thingA = thingProducer.<ThingA>getThing(); // compile error here
    }
}
Run Code Online (Sandbox Code Playgroud)

ThingProducer是原始类型,因为类有一个类型参数,但在调用时getThing我们不是引用类类型参数,而是提供方法类型参数。根据我对 JLS 的理解,这应该是合法的,但它给了我这个错误:

incompatible types: Object cannot be converted to ThingA
Run Code Online (Sandbox Code Playgroud)

如果我,错误就会消失

  • 除去<S>从ThingProducer
  • 或使getThing静态
  • 声明thingProducer ThingProducer<?>而不是原始类型ThingProducer

这是编译器错误吗?如果不是,JLS 中的什么规则定义了这种行为?

java generics raw-types language-lawyer

5
推荐指数
1
解决办法
830
查看次数

标签 统计

generics ×2

java ×2

raw-types ×2

language-lawyer ×1