首页 > 编程知识 正文

Java 三目表达式中的NullPointerException问题,java三目表达式

时间:2023-05-05 05:04:38 阅读:184694 作者:4495

Java 三目表达式中的NullPointerException问题 背景问题思考找资料反思

背景

旧系统改造。

问题 Integer rank = bpo.getLocalRank() != null ? Ints.tryParse(bpo.getLocalRank()) : 0

这段代码中。一眼看去,如果bpo.getLocalRank返回的空字符串,那么rank就会为null,没问题。

思考

但是运行一下,我们就发现报错了。

Exception in thread "main" java.lang.NullPointerException

根据前后代码分析,我们的bpo对象不可能为空。
在这个基础上,分析表达式,NPE错误不可能从Ints.tryParse中产生。那么NPE从那里来的呢。
想了下NPE错误只可能从Ints.tryParse(bpo.getLocalRank())中导致的。但是这个为什么会导致NPE错误呢。联合上下文。三目表达式,第3位参数位 为 primitive type 。是不是这个参数导致第二位参数的自动拆箱呢,是不是会和赋值表达式一样,存在默认类型转换。
是不是验证一下。代码改成如下

Integer rank = bpo.getLocalRank() != null ? Ints.tryParse(bpo.getLocalRank()) : Integer.valueOf(0);

没报错。那么问题就定位了。

找资料

确定了原因。就去找文档,找 Java规范。链接 ^1
中有一段描述 Numeric Conditional Expressions的。具体如下

15.25.2. Numeric Conditional Expressions
Numeric conditional expressions are standalone expressions (§15.2).
The type of a numeric conditional expression is determined as follows:
If the second and third operands have the same type, then that is the type of the conditional expression.
If one of the second and third operands is of primitive type T, and the type of the other is the result of applying boxing conversion (§5.1.7) to T, then the type of the conditional expression is T.

很明显。如果三目运算符,一个是基本类型,一个是the result of applying boxing conversion (§5.1.7) to T。那么结果就是 T,也就是int类型。也就触发了我们的自动拆箱。并导致报错。
我们再反编译一下用jd-gui打开。看到类似如下代码。也得到了印证。

Integer localInteger2 = Integer.valueOf("123".equals("123") ? localObject.intValue() : 0); 反思 好了。问题解决。这个问题反应的还是我们JVM知识缺乏。从表面觉得没问题。没有深入了解JVM机制。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。