在调用instanceof之前需要进行空检查(Is null check needed before calling instanceof?)

编程入门 行业动态 更新时间:2024-10-28 03:30:10
在调用instanceof之前需要进行空检查(Is null check needed before calling instanceof?)

将null instanceof SomeClass返回false或抛出NullPointerException

Will null instanceof SomeClass return false or throw a NullPointerException?

最满意答案

不,在使用instanceof之前不需要空检查。

如果x为null则表达式x instanceof SomeClass为false 。

从Java语言规范, http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.20.2

“在运行时,如果RelationalExpression的值不为null,并且可以将引用转换为ReferenceType,而不引发ClassCastException,则instanceof运算符的结果为true,否则结果为false。

所以如果操作数为null,结果为false。

No, a null check is not needed before using instanceof.

The expression x instanceof SomeClass is false if x is null.

From the Java Language Specification, section 15.20.2, "Type comparison operator instanceof":

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

更多推荐

本文发布于:2023-07-28 22:34:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1309771.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:null   instanceof   check   calling   needed

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!