在原始类类型上忽略的显式方法类型参数;编译器错误? [英] Explicit method type parameter ignored on a raw class type; compiler bug?
本文介绍了在原始类类型上忽略的显式方法类型参数;编译器错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在使用显式类型参数调用泛型方法时遇到编译器错误,好像未考虑显式类型参数一样.最小的例子:
I am getting a compiler error calling a generic method with explicit type parameters, as if the explicit type parameter had not been taken into account. Minimal example:
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
}
}
ThingProducer
是原始类型,因为该类具有类型参数,但是在调用getThing
时,我们没有引用 class 类型参数,而是提供了方法类型参数.根据我对JLS的理解,这应该是合法的,但这给了我这个错误:
ThingProducer
is a raw type since the class has a type parameter, but in calling getThing
we are not referencing the class type parameter, but instead providing the method type parameter. Per my understanding of the JLS, this should be legal, but it gives me this error:
incompatible types: Object cannot be converted to ThingA
如果我消失
- 从
ThingProducer
中删除 - 或将
getThing
设为静态 - 声明
thingProducer ThingProducer<?>
而不是原始类型ThingProducer
<S>
- remove the
<S>
fromThingProducer
- or make
getThing
static - declare
thingProducer ThingProducer<?>
instead of the raw typeThingProducer
这是编译器错误吗?如果不是,那么JLS中的哪个规则定义了此行为?
Is this a compiler bug? If not, what rule in the JLS defines this behavior?
推荐答案
查看全文