在调用 instanceof 之前是否需要进行空检查? [英] Is null check needed before calling instanceof?
问题描述
null instanceof SomeClass
会返回 false
还是抛出 NullPointerException
?
Will null instanceof SomeClass
return false
or throw a NullPointerException
?
推荐答案
不需要,在使用 instanceof 之前不需要空检查.
No, a null check is not needed before using instanceof.
如果 x
为 null
,则表达式 x instanceof SomeClass
为 false
.
The expression x instanceof SomeClass
is false
if x
is null
.
Java 11 语言规范在 第 15.20.2 节,类型比较运算符 instanceof".(Java 17 不那么简洁地表达了这一点,在instanceof模式匹配的引入之后.)
The Java 11 Language Specification expresses this concisely in section 15.20.2, "Type comparison operator instanceof". (Java 17 expresses this less concisely, after the introduction of instanceof patternmatching.)
"在运行时,结果instanceof
运算符为 true
如果RelationalExpression 的值是不是 null
并且引用可能是强制转换为 ReferenceType不引发 ClassCastException
.否则结果为false
."
"At run time, the result of the
instanceof
operator istrue
if the value of the RelationalExpression is notnull
and the reference could be cast to the ReferenceType without raising aClassCastException
. Otherwise the result isfalse
."
所以如果操作数为空,则结果为假.
So if the operand is null, the result is false.
这篇关于在调用 instanceof 之前是否需要进行空检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!