我在调用具有显式类型参数的泛型方法时遇到编译器错误,就好像未考虑显式类型参数一样。最小的例子:
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>从ThingProducergetThing静态thingProducer ThingProducer<?>而不是原始类型ThingProducer这是编译器错误吗?如果不是,JLS 中的什么规则定义了这种行为?