Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

null instanceof SomeClass返回false还是抛出NullPointerException

  ask by Johan Lübcke translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
594 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

(不,使用instanceof之前不需要进行空检查。)

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

(如果xnull则表达式x instanceof SomeClassfalse 。)

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

(根据Java语言规范的第15.20.2节“类型比较运算符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 ."

(“在运行时,结果instanceof运算符是true ,如果RelationalExpression的值null ,并引用可以转换为引用类型不提高一个ClassCastException 。否则,结果是false 。”)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...