null instanceof SomeClass
返回false
还是抛出NullPointerException
?
No, a null check is not needed before using instanceof.
(不,使用instanceof之前不需要进行空检查。)
The expression x instanceof SomeClass
is false
if x
is null
.
(如果x
为null
则表达式x instanceof SomeClass
为false
。)
From the Java Language Specification, section 15.20.2, "Type comparison operator instanceof" :
(根据Java语言规范的第15.20.2节“类型比较运算符instanceof” :)
"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
."(“在运行时,结果
instanceof
运算符是true
,如果RelationalExpression的值不null
,并引用可以转换为引用类型不提高一个ClassCastException
。否则,结果是false
。”)
So if the operand is null, the result is false.
(因此,如果操作数为null,则结果为false。)