在调用instanceof之前是否需要空的检查?


请问null instanceof SomeClass返回false或者抛出一个NullPointerException

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

如果xnull,表达式x instanceof SomeClassfalse
从Java语言规范,在http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.20.2

“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 (
§15.16) to the ReferenceType without raising a ClassCastException. Otherwise
the result is false.”

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

使用空引用作为第一个操作数,并返回false。 (试用1分钟)

未经作者同意,本文严禁转载,违者必究!