Strange Java Compiler Warning: Invalid "Potential Invalid Access Warning"

(JDK 1.6.0_23, Eclipse 3.7.0 with the warning level "Potential null access pointer" in "Warning"). Consider the following code example:

Object obj = null; for (;;) { obj = getObject(); if (obj != null) break; Thread.sleep(25); } obj.toString(); 

I get the following warning on the last line: Potential null pointer access: The variable obj may be null at this location . Is there a real way for obj actually be null or why does the compiler think so?

+2
source share
5 answers

The compiler sees this as the potential that the object will not be initialized. In fact, it is not possible to see that the condition for interrupting the cycle is that the object is not zero, or it will run forever or until it becomes zero. I am only warning about the JDK you mentioned. Using a more updated version, this warning does not appear.

+3
source

I would say that the compiler sees this as:

 Object obj = null; [Too dumb to interpret this loop] obj.toString(); 

That way, obj.toString () can be empty if you cannot interpret what the loop does.

For example, you can trick the compiler by replacing:

 void x(int x){ return; x++; //error unreachable code } 

with

 void x(int x){ if(true) return; x++; //compiles } 
+8
source

It seems that the compiler cannot parse the code very well. It actually cannot "start" it and understand that your if prevents null access. I played a little with the code and found the following equivalent version that does not raise a warning:

  Object obj = null; do { obj = getObject(); if (obj == null) { Thread.sleep(25); } } while (obj == null); obj.toString(); 

Yes, I know that this version performs 2 null checks for each iteration of the loop instead of one. So, you need to change your code, add @SuppressWarning to your code or remove Thread.sleep(25)

+4
source

This is an improved version of AlexR code, which, in my opinion, is a good solution to the problem, and also improves code readability. My version has a second line obj = getObject(); but a second check is not needed, so it should be more complete.

 Object obj = null; obj = getObject(); while (obj == null) { Thread.sleep(25); obj = getObject(); } obj.toString(); 
+3
source

I know this is an old thread, but what about this? I find it more readable than the Koraktor and AlexR versions.

 Object obj = null; for (obj=getObject(); obj==null; obj=getObject()) { Thread.sleep(25); } obj.toString(); 

But in my code, I usually enable "Enable" assert "in zero analysis in the eclipse compiler settings and add assert. Therefore, I do not need to change the control flow and at the same time avoid the warning:

 Object obj = null; while (true) { obj = getObject(); if (obj != null) break; Thread.sleep(25); } assert obj!=null; obj.toString(); 
0
source

Source: https://habr.com/ru/post/1484797/


All Articles