java 菱形的一半_java – 通用参数:只有菱形运算符似乎可以工作

背景:问题出现在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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值