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

查看:18
本文介绍了在调用 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.

如果 xnull,则表达式 x instanceof SomeClassfalse.

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 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."

所以如果操作数为空,则结果为假.

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

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

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