在调用instanceof之前需要进行空检查吗? [英] Is null check needed before calling instanceof?
问题描述
将 null instanceof SomeClass
返回 false
或抛出 NullPointerException
?
推荐答案
不,在使用instanceof之前不需要进行空检查。
No, a null check is not needed before using instanceof.
表达式 x instanceof SomeClass
是 false
if x
是 null
。
来自Java语言规范, 第15.2.2节,类型比较运算符instanceof:
From the Java Language Specification, section 15.2.2, "Type comparison operator instanceof":
在运行时,
的结果如果 RelationalExpression 的
运算符为
值为
,则instanceoftrue
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
."
因此,如果操作数为null,则结果为false。
So if the operand is null, the result is false.
这篇关于在调用instanceof之前需要进行空检查吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!