gpt4 book ai didi

java - 为什么 int num = Integer.getInteger ("123") 会抛出 NullPointerException?

转载 作者:IT老高 更新时间:2023-10-28 11:27:07 26 4
gpt4 key购买 nike

以下代码抛出NullPointerException:

int num = Integer.getInteger("123");

我的编译器是否在 null 上调用 getInteger,因为它是静态的?这没有任何意义!

发生了什么事?

最佳答案

大局

这里有两个问题:

  • Integer getInteger(String) 没有做你认为它做的事情
    • 在这种情况下返回 null
  • Integerint 的赋值导致自动拆箱
    • 由于IntegernullNullPointerException被抛出

要将 (String) "123" 解析为 (int) 123,您可以使用例如int Integer.parseInt(String).

引用文献

整数 API 引用


Integer.getInteger

以下是文档中关于此方法的作用的内容:

public static Integer getInteger(String nm): Determines the integer value of the system property with the specified name. If there is no property with the specified name, if the specified name is empty or null, or if the property does not have the correct numeric format, then null is returned.

换句话说,该方法与将String解析为int/Integer值无关,而是与System.getProperty有关。方法。

诚然,这可能是一个相当大的惊喜。不幸的是,图书馆有这样的惊喜,但它确实教会了你一个宝贵的教训:总是查阅文档以确认方法的作用。

巧合的是,这个问题的一个变体出现在 Return of the Puzzlers: Schlock and Awe (TS-5186) 中。 , Josh Bloch 和 Neal Gafter 的 2009 JavaOne 技术 session 演示文稿。这是最后一张幻灯片:

The Moral

  • Strange and terrible methods lurk in libraries
    • Some have innocuous sounding names
  • If your code misbehaves
    • Make sure you're calling the right methods
    • Read the library documentation
  • For API designers
    • Don't violate the principle of least astonishment
    • Don't violate the abstraction hierarchy
    • Don't use similar names for wildly different behaviors

为了完整起见,还有这些方法类似于Integer.getInteger:

相关问题


关于自动拆箱

当然,另一个问题是 NullPointerException 是如何被抛出的。为了专注于这个问题,我们可以将代码片段简化如下:

Integer someInteger = null;
int num = someInteger; // throws NullPointerException!!!

这里引用 Effective Java 2nd Edition,Item 49:Prefer primitive types to boxed primitives:

In summary, use primitives in preference to boxed primitive whenever you have the choice. Primitive types are simpler and faster. If you must use boxed primitives, be careful! Autoboxing reduces the verbosity, but not the danger, of using boxed primitives. When your program compares two boxed primitives with the == operator, it does an identity comparison, which is almost certainly not what you want. When your program does mixed-type computations involving boxed and unboxed primitives, it does unboxing, and when your program does unboxing, it can throw NullPointerException. Finally, when your program boxes primitive values, it can result in costly and unnecessary object creations.

有些地方你别无选择,只能使用盒装图元,例如泛型,否则您应该认真考虑使用盒装原语的决定是否合理。

相关问题

关于java - 为什么 int num = Integer.getInteger ("123") 会抛出 NullPointerException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3123349/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com