奇怪的Java编译器警告:错误的“潜在的null访问警告”; [英] Strange Java compiler warning: incorrect "potential null access warning"
问题描述
(JDK 1.6.0_23,在警告中具有潜在的空指针访问警告级别的Eclipse 3.7.0)请考虑以下示例代码:
(JDK 1.6.0_23, Eclipse 3.7.0 with "Potential null pointer access" warning level at "Warning") Consider the following example code:
Object obj = null;
for (;;) {
obj = getObject();
if (obj != null) break;
Thread.sleep(25);
}
obj.toString();
我在最后一行收到以下警告:可能为空的指针访问:变量obj在此位置可能为空
。 obj
是否有任何真正的方法实际上是 null
,还是为什么编译器会这样认为?
I'm getting the following warning on the last line: Potential null pointer access: The variable obj may be null at this location
. Is there any real way for obj
to actually be null
or why the compiler thinks so?
推荐答案
编译器将其视为可能不会初始化该对象的可能性。确实无法看到循环中断的条件是该对象不为null,或者它将永远运行或直到不再为null。我只收到您提到的JDK的警告。使用更新的版本不会显示此警告。
The compiler is seeing this as a potential that the object will not be initialized. It is not really able to see that the loop breaking condition is that the object is not null or it will just run forever or until it is no longer null. I only get the warning on the JDK you mentioned. Using a more updated version this warning does not appear.
这篇关于奇怪的Java编译器警告:错误的“潜在的null访问警告”;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!