将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.
更多推荐
发布评论