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 typePath
as its type parameter,DirectoryStream<Path>
which comes fromFiles.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/