I encounter a strange situation that is currently not that clear to me:
When having the potential null pointer access warning enabled in Eclipse, I get warnings like in the following (the warnings are stick to the line preceding the corresponding comment):
protected Item findItemByName(String itemName, Items items) {
boolean isItemNameMissing = null == itemName || itemName.isEmpty();
boolean isItemsMissing = null == items || null == items.getItems() || items.getItems().isEmpty();
if (isItemNameMissing || isItemsMissing) {
return null;
}
// potential null pointer access: the variable items might be null at this location
for (Item item : items.getItems()) {
// potential null pointer access: the variable itemName might be null at this location
if (itemName.equals(item.getName())) {
return item;
}
}
return null;
}
The same happens to me if I check for null
using Guava's Preconditions like
Preconditions.checkArgument(argument != null, "argument must not be null");
Where I can understand that in the latter case a flow analysis for checking when the IllegalArgumentException
will happen might be too difficult/expensive or even impossible I in turn do not understand why the compiler raises the warning at all (if I remove the checks they disappear).
Can one maybe explain how the potential null pointer access is accomplished and why it is raised in both of the cases? Or at least point me to the direction.
In the meanwhile I have a look and see whether I find it out myself...
Addendum
I've kind of broken it down to the bare core of the case. Given the following class, the warning only shows up in the method sample2
(as pointed out by the comment again). Please note that the method sample3
does not trigger the warning either.
public class PotentialNullPointerAccess {
public void sample1(final String aString) {
if (aString == null) {
return;
}
System.out.println(aString.length());
}
public void sample2(final String aString) {
boolean stringIsNull = null == aString;
if (stringIsNull) {
return;
}
// Potential null pointer access: The variable aString might be null at this location
System.out.println(aString.length());
}
public void sample3(final String aString) {
System.out.println(aString.length());
}
}
null
checks. I am not seeing a big issue in this since I can just disable the warning. But I want to understand the why - if reasonable, admittedly. – Sperrylitesample3
method that has no warning... – Sperrylite