将 Null-Object 拆箱为原始类型会导致 NullPointerException,好吗? [英] Unboxing Null-Object to primitive type results in NullPointerException, fine?
问题描述
这个代码段抛出一个 NullPointerException
因为它被拆箱为原始类型并且 Long.longValue()
被调用,对吧?
This snippet throws an NullPointerException
due to the fact that its unboxed to a primitive type and Long.longValue()
is called, right?
如果您有这样的片段,那就更容易了:
Thats even easy to see if you have a snippet like this:
long value = (Long) null;
但是 NullPointerException
在更复杂的情况下更难得到:
But the NullPointerException
is even harder to get in a more complex situation like this:
long propertyValue = (Long) obj.getProperty(propertyModel.getName());
那么,Java 编译器是否有可能从中生成更舒适的异常?我更喜欢 IllegalArgumentException
带有类似 您正在尝试将空对象转换为原始类型的消息,这是不可能的!"
So isn't there any possibility for the Java-Compiler to make a more comfortable Exception out of this? I would prefer an IllegalArgumentException
with a message like "You're trying to cast a null-Object into a primitive type, this can't be done!"
这样不是更合适吗?你怎么认为?这在运行时甚至可能吗?我们能确定这个演员表吗?我还没有看过java字节码.也许它可以用于解决方案.
Wouldn't this be more appropriate? What do you think? Is this even possible at runtime? Are we able to determine this cast? I haven't yet looked at the java bytecode. Maybe it could be used in a solution.
这个问题可以回答:我想知道是否有可能实现这种行为!
This question can be answered: I'd like to know if it's possible to achieve this behaviour!
推荐答案
根据Java 语言规范,通过调用Number.longValue()
、Number.intValue()
进行拆箱等.没有发生特殊的字节码魔术,这与您手动调用这些方法完全相同.因此,NullPointerException
是拆箱 null
的自然结果(实际上是 JLS 强制要求的).
According to the Java language specification, unboxing happens via calling Number.longValue()
, Number.intValue()
, etc. There is no special byte code magic happening, it's exactly the same as if you call those methods manually. Thus, the NullPointerException
is the natural result of unboxing a null
(and in fact mandated by the JLS).
抛出不同的异常需要在每次拆箱转换期间检查 null
两次(一次确定是否抛出特殊异常,一次隐式,当方法实际上是称为).我想语言设计者认为它的用处不足以保证这一点.
Throwing a different exception would require checking for null
twice during every unboxing conversion (once to determine whether to throw the special exception, and once implicitly when the method is actually called). I suppose the language designers didn't think it useful enough to warrant that.
这篇关于将 Null-Object 拆箱为原始类型会导致 NullPointerException,好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!