[英]Why does Throwable.getCause check to see if 'cause' is 'this' before returning `null` instead of just returning the cause directly?
今天我有理由进入Throwable.getCause
的源代码,并且在该方法中看到此代码时有点惊讶:
public synchronized Throwable getCause() {
return (cause==this ? null : cause);
}
这是来自 Java 1.8,但在我看过的更高版本中看起来相同。
我的问题是:为什么不简单地return cause
并完成它?
它不是将cause
与null
进行比较,而是将cause
与this
进行比较。 为避免循环,如果cause
是this
,则返回 null。
编码:
public synchronized Throwable getCause() {
return (cause==this ? null : cause);
}
说如果cause
是this
返回null
否则返回cause
(它也可能是null
因为它发生。
故事是这样开始的: private Throwable cause = this;
我相信所有版本>=1.4 都是一样的。 这将原因初始化为这个对象!
目的是Throwable
对象是不可变的,但它提供了一个方法void initCause(Throwable cause)
只能调用一次来初始化原因或由构造函数初始化的原因。
正如文档所解释的那样,允许将原因链接到在引入cause
之前添加的子类,这些子类不包含在其构造函数之一中。
因此,该类以某种方式想知道是否已调用initCause
并抛出IllegalStateException
如果有)(我的评论):
public Throwable initCause(Throwable cause) {
if (cause == this) //Illogical! An exception can't be self caused!
throw new IllegalArgumentException();
if (this.cause != this)// false if cause has been initialised 'properly'.
throw new IllegalStateException();
this.cause = cause;
return this;
}
该类使用cause==this
来指示未设置cause
。 它不能使用cause==null
因为null
是一个有效值。 所以它使用了cause==this
的异常状态,因为主动设置cause
到this
是自引发异常的不合逻辑状态。
它确实有效。 但这真的是个好主意吗? 我说不是。 它将“原因未设置”和“原因已设置并设置为null
”的状态混为一谈。 一个不太扭曲的设计只是引入了一个标志private boolean isCauseSet=false;
并在initCause
被调用或设置它的构造函数被调用时设置它。
我们在Throwable
看到的复杂代码只不过是避免了boolean
。 在Throwable
保存单个boolean
字段似乎真的不值得打扰。 没有任何有用的应用程序会在流通中拥有如此多的Throwable
对象,因此它很重要。
该null
值由printStackTrace
方法使用, 例如,在调用stackTraceString
方法时,第 421..450行标识堆栈跟踪的输出应何时完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.