Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
343 views
in Technique[技术] by (71.8m points)

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

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;

But the NullPointerException is even harder to get in a more complex situation like this:

long propertyValue = (Long) obj.getProperty(propertyModel.getName());

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!"

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...