在调用instanceof之前需要进行空检查吗? [英] Is null check needed before calling instanceof?

查看:639
本文介绍了在调用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
值为
,则instanceof
运算符为 true null 并且引用可能是
强制转换为 ReferenceType
而不会提高 ClassCastException
否则结果为 false

"At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast to the ReferenceType without raising a ClassCastException. Otherwise the result is false."

因此,如果操作数为null,则结果为false。

So if the operand is null, the result is false.

这篇关于在调用instanceof之前需要进行空检查吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆