三生石@ 2010-06-01 13:53 采纳率: 100%
浏览 424
已采纳

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

Will null instanceof SomeClass return false or throw a NullPointerException?

转载于:https://stackoverflow.com/questions/2950319/is-null-check-needed-before-calling-instanceof

  • 写回答

7条回答 默认 最新

  • 游.程 2010-06-01 14:05
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

  • ¥15 vscode的问题提问
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM