背景:问题出现在this answer(答案的第一个修订版,确切地说).此问题中提供的代码被简化为最低限度来解释问题.
假设我们有以下代码:
public class Sample> {
public static Sample extends Sample>> get() {
return new Sample<>();
}
public static void main(String... args) {
Sample extends Sample>> sample = Sample.get();
}
}
它在没有警告的情况下编译并执行正常.但是,如果有人试图以某种方式定义推断类型的返回new Sample<>();在get()中显式编译器抱怨.
到目前为止,我的印象是钻石操作符只是一些语法糖,不能写出显式类型,因此总是可以用一些显式类型替换.对于给定的示例,我无法为返回值定义任何显式类型以使代码编译.是否可以明确定义返回值的泛型类型,或者在这种情况下是否需要菱形运算符?
下面是我使用相应的编译器错误显式定义返回值的泛型类型的一些尝试.
返回新样本结果是:
Sample.java:6: error: type argument Sample is not within bounds of type-variable T
return new Sample();
^
where T is a type-variable:
T extends Sample declared in class Sample
Sample.java:6: error: incompatible types: Sample cannot be converted to Sample extends Sample>>
return new Sample();
^
返回新样本>结果是:
Sample.java:6: error: type argument Sample> is not within bounds of type-variable T
return new Sample>();
^
where T is a type-variable:
T extends Sample declared in class Sample
返回新样本< Sample<>>();结果是:
Sample.java:6: error: illegal start of type
return new Sample>();
^
解决方法:
JLS简单地说:
If the type argument list to the class is empty — the diamond form <> — the type arguments of the class are inferred.
那么,是否有一些能够满足解决方案的推断X?是.
当然,为了明确定义这样的X,你必须声明它:
public static > Sample extends Sample>> get() {
return new Sample();
}
显式样品< X>与返回类型Sample>,因此编译器很高兴.
事实上,返回类型是混乱的样本>是一个完全不同的故事.
标签:java,generics,type-inference
来源: https://codeday.me/bug/20190910/1800769.html