java - 为什么 java.nio.file.DirectoryStream 使用无限泛型?

标签 java generics

DirectoryStream的唯一用法我见过的使用类型 Path作为其类型参数,DirectoryStream<Path>来自Files.newDirectoryStream(Path) .

此外,由于 documentation 中的以下语句,我不明白为什么它允许任何类型:

If hasNext method returns true, and is followed by a call to the next method, it is guaranteed that the next method will not throw an exception due to an I/O error, or because the stream has been closed.

这一定意味着它会检查 Path可以预先访问,因此不能是通用类型。

最佳答案

Why does java.nio.file.DirectoryStream use unbounded generics?

The only usage of DirectoryStream that I have seen uses the type Path as its type parameter, DirectoryStream<Path> which comes from Files.newDirectoryStream(Path).

如果你看SecureDirectoryStream , 该接口(interface)扩展了 DirectoryStream有一个无限泛型。然而,唯一的具体实现SecureDirectoryStream也用 Path 参数化.

所以,最合理的解释是:

  • 参数化是为了实现 future 可能的增强,或者
  • 原本打算提供 File 的目录流, 但它被放弃了......完全摆脱参数为时已晚。

无论哪种方式,目前该参数都是无害的异常。

This must mean it checks whether the Path is accessible beforehand and therefore cannot be a generic type.

参数可能是无界的,因为 Path 没有合适的通用 super 接口(interface)和 File .它不能真的是任何类型的事实是......不幸的是,但绝不是唯一的。在其他情况下,隐含的类型要求未在静态类型中表达。例如:

  • ObjectOutputStream.writeObject(Object)如果对象未实现 Serializable,方法将失败.

  • Arrays.sort(Object[])如果数组元素没有全部实现 Comparable,方法将失败.

而且我希望还有其他示例,其中泛型类的某些参数化没有什么意义。

关于java - 为什么 java.nio.file.DirectoryStream 使用无限泛型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41660795/

相关文章:

java - 从组合框中选择时如何突出显示特定标签?

java - 如何比较Java中的字符串?

java - 返回集合或列表中的最高整数

java - 32/64 位 eclipse

java - 通用 Spring Bean - 复制类型参数

java - 返回类型之前泛型的目的是什么

java - 获取特定枚举的类型

java - 无法创建外部类<TO>.内部类的通用数组

java - <ClassName> 在 Java 中代表什么?

.net - 从列表中过滤或删除(T 个)