简体   繁体   中英

Potential null pointer access in Eclipse - seemingly trivial example

I have this very basic piece of code and Eclipse gives me the "potential null pointer access" warning/error.

public class PotentialNull {
    public void test(final String nullableString) {
        boolean isNotNull = nullableString != null;

        if (nullableString != null) {
            // No problem
            System.out.print(nullableString.hashCode());
        }

        if (isNotNull) {
            // Potential null pointer access: The variable nullable may be null at this location
            System.out.print(nullableString.hashCode());
        }
    }
}

As you can see in the example, the compiler knows that inside the first if statement, nullableString can't be null. However, in the second it doesn't and I really wouldn't have thought this would be too tough to figure out.

Can someone please confirm that this is not specific to my system/setup?

I know, I could suppress warnings etc. but I'm really wondering whether this might be a bug. Or am I overlooking something?

Another question about this seems to address a much more complex situation so I hope it's ok I'm asking again.

This is described in Eclipse bug 260293 one of several duplicates closed as Won't Fix.

The bug basically says that Eclipse does not track the correlation between the variables isNotNull and nullableString so it doesn't know that the value can't be null.

use conditional operator while assigning the boolean varaible isNotNull. change the line

boolean isNotNull = nullableString != null;

to

boolean isNotNull = (if(nullableString != null)?True:False);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM