键入带有多个边界的参数 [英] Type parameter with multiple bounds

查看:84
本文介绍了键入带有多个边界的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段代码编译:

  import java.io.Serializable; 
import java.util.Arrays;
class Test< T扩展了数组&序列化> {}

但是如果我用

替换最后一行

  class Test< T extends Serializable&阵列与GT; {} 

我得到了此处预期的界面。为什么?

解决方案

From JLS第4.4节


每个声明为类型参数的类型变量都有一个绑定。如果没有为类型变量声明绑定,则假定为Object。如果声明了一个绑定,它包含以下任一项:




  • 单个类型变量T或


  • 类或接口类型T可能跟随接口类型I1& ...& In。




如果任何类型I1 ... In是类类型,则是编译时错误或类型变量。

所以基本上,如果你的界限包含一个类,它必须是第一个 (既然 Arrays 不能被实例化,目前还不清楚为什么要 / em>一个包含它的边界,介意你......这仅仅是一个例子吗?)

This code compiles:

import java.io.Serializable;
import java.util.Arrays;
class Test<T extends Arrays & Serializable> { }

but if I replace the last line with

class Test<T extends Serializable & Arrays> { }

I get "interface expected here". Why?

解决方案

From section 4.4 of the JLS:

Every type variable declared as a type parameter has a bound. If no bound is declared for a type variable, Object is assumed. If a bound is declared, it consists of either:

  • a single type variable T, or

  • a class or interface type T possibly followed by interface types I1 & ... & In.

It is a compile-time error if any of the types I1 ... In is a class type or type variable.

So basically, if your bounds include a class, it has to be the first bound.

(Given that Arrays can't be instantiated, it's unclear why you would want a bound including it, mind you... was this just an example?)

这篇关于键入带有多个边界的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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