FileNotFoundException 中定义的私有构造函数?

Private constructor defined in FileNotFoundException?

我偶然发现了这个网站:http://resources.mpi-inf.mpg.de/d5/teaching/ss05/is05/javadoc/java/io/FileNotFoundException.html

class FileNotFoundException 定义了三个构造函数:

    FileNotFoundException()
          Constructs a FileNotFoundException with null as its error detail message.

    FileNotFoundException(String s)
          Constructs a FileNotFoundException with the specified detail message.

    private FileNotFoundException(String path, String reason)
          Constructs a FileNotFoundException with a detail message consisting of the given pathname string followed by the given reason string.

但是最后一个构造函数被定义为private?

同样,在这里:http://www.docjar.com/html/api/java/io/FileNotFoundException.java.html 我们可以看到完整的 class 定义。没有其他代码,所以单例模式显然没有用于那种情况,我们也看不到,为什么要阻止在对象外部实例化 class ,也不是工厂方法,static (实用程序 class) 方法或仅常量 class。

我是 C# 开发人员,所以我可能不知道这里发生的一些事情,但我仍然对为什么它被定义为私有、它的用途以及是否有任何示例或用途感兴趣最后一个构造函数的情况。

评论提到:

This private constructor is invoked only by native I/O methods.

有人再详细解释一下吗?

请记住:JVM 的许多库都是用 Java 编写的,例如那个例外。但是在与 "the rest of the world" 交互时;迟早 Java 不会再做任何事 - 需要讨论 C/C++ 才能进行 真正的 系统调用。

意思:某些与文件IO相关的操作在Java中无法完全实现。因此 native 代码进入(编译的二进制文件)。但当然,这样的调用也可能失败。但是随后需要一种在 Java 方面传达这一点的方法 - 换句话说:需要抛出异常。

鉴于您引用的评论,这似乎很简单:当某些 IO 相关 native 操作失败时;他们将使用该私有构造函数创建异常,然后在 "you" 处抛出该异常。而且native方法可以调用private方法!

编辑:但是在查看 implementation 时 - 实际上 没有任何内容 关于该构造函数私人演员会创造。

private FileNotFoundException(String path, String reason) {
  super(path + ((reason == null)
             ? ""
             : " (" + reason + ")"));
}

所以,我个人的猜测:这甚至可能是一些 "leftover"。 15年前有某种意义的东西;但不再属于 "real meaning"。或者更简单,一个 convenience 方法允许本机代码传递 null 或非 null 原因字符串。

有问题的构造函数是私有的,因此没有其他 class 可以使用它来初始化实例。原则上,它可以被 class 本身使用——当一个构造函数打算被另一个构造函数或工厂方法调用时,这种事情并不罕见。

然而,在这种情况下,文档提供了不同的原因,您实际上引用了该原因:

This private constructor is invoked only by native I/O methods.

这对我来说似乎很清楚,但我想您的困惑可能围绕着 Java 访问控制的细节——特别是,它不适用于本机方法。因此,实现各种 I/O 功能的本机方法可以通过私有构造函数实例化 FileNotFoundException,而不管它们属于哪个 class。