Unboxing Null-Object to primitive type results in NullPointerException, fine?

后端 未结 4 1673
Happy的楠姐
Happy的楠姐 2020-12-03 09:29

This snippet throws an NullPointerException due to the fact that its unboxed to a primitive type and Long.longValue() is called, right?

Tha

4条回答
  •  天命终不由人
    2020-12-03 10:04

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

    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.

提交回复
热议问题