[英]Is there any reason for expression like !Boolean.FALSE.equals()?
When browsing the Spring's source code, I encountered code like if (!Boolean.FALSE.equals(pv.conversionNecessary)) {...}
在浏览 Spring 的源码时,遇到了
if (!Boolean.FALSE.equals(pv.conversionNecessary)) {...}
After some research, I also found codes like !Boolean.FALSE.equals
and !Boolean.TRUE.equals
exist in other open-source projects too.经过一番研究,我还发现其他开源项目中也存在诸如
!Boolean.FALSE.equals
和!Boolean.TRUE.equals
类的代码。
I wonder what's the possible reasons for not using the apparently concise expression?我想知道不使用明显简洁的表达的可能原因是什么?
There are various reasons why this kind of thing might be necessary.这种事情可能有必要的原因有多种。
In this example, pv
is an instance of PropertyValue
which declares the conversionNecessary
as follows:在这个例子中,
pv
是一个PropertyValue
的实例,它声明了conversionNecessary
如下:
/** Package-visible field that indicates whether conversion is necessary. */
@Nullable
volatile Boolean conversionNecessary;
( source code ) ( 源代码)
From this, we can infer that it is not unexpected for conversionNecessary
to be null
.由此我们可以推断,
conversionNecessary
为null
并不意外。
So ... the verbose form if (!Boolean.FALSE.equals(pv.conversionNecessary)) {...}
is dealing with the null
case.所以......冗长的形式
if (!Boolean.FALSE.equals(pv.conversionNecessary)) {...}
正在处理null
情况。 Boolean.FALSE.equals(null)
is false
. Boolean.FALSE.equals(null)
为false
。
By contrast, the more concise form if (!pv.conversionNecessary) {...}
would throw an NPE.相比之下,更简洁的形式
if (!pv.conversionNecessary) {...}
会抛出 NPE。
It is also worth noting that since conversionNecessary
is volatile
here, an alternative version that did an explicit null
check would need to use a temporary variable to avoid race conditions;还值得注意的是,由于
conversionNecessary
在这里是volatile
,执行显式null
检查的替代版本将需要使用临时变量来避免竞争条件; eg例如
Boolean necessary = pv.conversionNecessary;
if (necessary == null || necessary) { ... }
Another scenario where you might do this kind of thing is if the declared type of the variable is Object
rather than Boolean
.您可能会做这种事情的另一种情况是,如果变量的声明类型是
Object
而不是Boolean
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.