是否可以在Java中为类型参数指定上限和下限约束? [英] Is it possible to specify both upper and lower bound constraints on type parameters in Java?

查看:346
本文介绍了是否可以在Java中为类型参数指定上限和下限约束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在Java中为类型参数指定上限和下限约束?



我发现在Sun的论坛中讨论这个问题(显然在泛型特性完成之前),但是没有最终的回答。

总之,是否有一个有效的语法来做到这一点:

  public class MyClass< T extends Number super Integer> 

解决方案 div>

我不这么认为 - 就我从语言规范中可以看出的来说,super仅适用于通配符类型。通配符的语法也表明你只能有一个通配符绑定 - 所以你不能使用这样的事情:

  //无效
void foo(List< ;? extends Foo super Bar> list)

即使这两个都没问题:

  // Valid 
void foo(List< ;? extends Foo> list)
$ b $ //有效的
void foo(List< ;? super bar> list)

正如注释中指出的那样,可能有多个上限边界 - 但仅限于类型参数和转换表达式。例如:

  // Valid 
< T extends Number&可比> void foo(List< T> list)


Is it possible to specify both upper and lower bound constraints on type parameters in Java?

I found a conversation in Sun's forum in which this issue was discussed (apparently before the generics feature was finalized), but there was no final answer.

In summary, is there a valid syntax to do this:

public class MyClass<T extends Number super Integer>

?

解决方案

I don't believe so - as far as I can tell from the language specification, "super" is only valid for wildcard types in the first place. The syntax for wildcards also suggests you can only have one wildcard bound, too - so you can't use something like this either:

// Invalid
void foo(List<? extends Foo super Bar> list)

Even though both of these are okay:

// Valid
void foo(List<? extends Foo> list)

// Valid
void foo(List<? super Bar> list)

As noted in comments, it's possible to have multiple upper bounds - but only for type parameters and cast expressions. For example:

// Valid
<T extends Number & Comparable> void foo(List<T> list)

这篇关于是否可以在Java中为类型参数指定上限和下限约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆