将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-Compiler没有任何可能使Exception更加舒适?我希望 IllegalArgumentException
带有像这样的消息你试图将null-Object转换为基本类型,这是不可能的!
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()$ c $进行拆箱c>,
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屋!