查看Integer.parseInt(String s, int radix)
(Java 8,1.8.0_131)的源代码时,我发现以下注释块:
/*
* WARNING: This method may be invoked early during VM initialization
* before IntegerCache is initialized. Care must be taken to not use
* the valueOf method.
*/
虽然我理解第一部分关于IntegerCache的内容,但我不明白为什么会有关于valueOf
的警告,以及在这个上下文中为什么要这样警告。
我知道valueOf()
依赖于parseInt()
,但我仍然不明白为什么会有这个警告。
有人能够解释一下这个注释究竟是在警告我什么(以及在哪些情况下不能使用valueOf),以及可能会发生什么问题吗?
编辑:
Integer.valueOf(int i)中的代码似乎自从下面评论中的另一个问题被问出来后已经更改了,它现在是
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
并且在此之前应该免于断言错误。