InvocationTargetException

InvocationTargetException

按照javadocsInvocationTargetException.getCause()可以为null:



但是文档还说它包装了一个现有的异常:



因此在我看来InvocationTargetException.getCause() 永远不可能是null

我想念什么吗?

更新

是的,我错过了一些事情-InvocationTargetException的默认构造函数将导致getCause()为null。

我现在的问题是,为什么要为此类提供一个默认的构造函数。是否存在用例需要以空原因引发异常的用例?

最佳答案

所以。

@xtravar对my (much) earlier answer的评论已引起对这个问题的另一种观察。我可能就知道了。请多多包涵。
InvocationTargetException最早是在Java中引入的。至少早在某些JDK 1.1.X上,它可以追溯到between February 1997 to December 1998的任何地方。我怎么知道这么老?毕竟,该类上没有@since 1.1标记。
我碰巧在serialVersionUID字段上看到以下javadoc:

/**
 * Use serialVersionUID from JDK 1.1.X for interoperability
 */

正确的。所以呢?
因此,根据Throwable.getCause()的文档,InvocationTargetException最终继承了:
While it is typically unnecessary to override this method, a subclass can
override it to return a cause set by some other means. This is appropriate
for a "legacy chained throwable" that predates the addition of chained
exceptions to Throwable.
...
@since 1.4

现在,请将其与InvocationTargetException类文档的以下注释结合起来:
As of release 1.4, this exception has been retrofitted to conform to
the general purpose exception-chaining mechanism.  The "target exception"
that is provided at construction time and accessed via the
getTargetException() method is now known as the cause,
and may be accessed via the Throwable.getCause() method,
as well as the aforementioned "legacy method."

看到我要去哪里?
关于Throwable.getCause()的注释完全针对InvocationTargetException(至少)。在将异常链接引入InvocationTargetExcpetion之前,使用Throwable链接异常。

如前所述,当对InvocationTargetException进行改造时,我认为语言设计人员希望:
  • 防止了InvocationTargetException具有两种不同的“原因”的可能性-一种存储在target中,另一种存储在cause中;还是
  • 与依赖target字段的现有代码向后兼容。

  • 这就是为什么他们将target字段保留为真正使用并实现了任何现有构造函数的原因,以便cause字段永久保留为null的原因。当然,getCause()InvocationTargetException实现会返回target作为原因。

    所以要回答



    不完全是,不是要使用该类,也不应该使用该类。

    但是,这个问题仍然存在:



    (和this constructor seems to exist ever since)

    我倾向于认为此类实际上是对null宽容的。毕竟,public构造函数允许null作为Throwable target 。作为设计者,如果您已经允许这样做,则可以添加protected默认构造函数,该构造函数将null显式分配给target,从而使继承类可以构造所需的类。

    这也回答了原始问题:



    是的。 InvocationTargetException实际上确实打算具有非null targetcause。但是,这里的“遗漏”是不幸的是target(因此还有cause)可以是null,因为该类中的任何内容都不强制它。

    09-27 08:10