Java中使用instanceof判断类型时?
答案是不需要,在调用instanceof之前不需进行null值判断,为什么呢?
我们来看jdk文档中的说明
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并且能够强转不抛类转换异常则返回true,否则返回false。
那么定义
Object a = null;
a instanceof Integer 返回false。
Copyright © 广州京杭网络科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州京杭网络科技有限公司 版权所有