Finding potential NullPointerExceptions

Viewed 38

I'm trying to analyse individual methods to see if there's anywhere in a codebase that they could cause a NullPointerException. For example, given the following 3 methods

@Nullable
public UUID getId() {
    return id;
}

public Object callDirectly() {
    return getId();
}

public Object callIndirectly() {
    return callDirectly().toString();
}

It's obvious that callIndirectly will cause a NullPointerException if id is null. However, it seems that IntelliJ's "@NotNull/@Nullable problem" inspection isn't smart enough to figure this out. If I change the code to

@Nullable
public UUID getId() {
    return id;
}

public Object callDirectly() {
    return getId().toString();
}

public Object callIndirectly() {
    return callDirectly().toString();
}

the IntelliJ inspection highlights callDirectly as a potential NullPointerException, so I guess only direct calls to @Nullable methods are considered, which is fairly useless.

I've also looked at IntelliJ's data flow analysis feature, but it doesn't seem to be able to answer my question, i.e. "is there anywhere in this codebase that a call to this @Nullable method could cause a NullPointerException"?

I realise there are limits to static analysis, e.g. reflective calls to methods cannot be reasoned about, but it seems that there ought be a tool that can detect the potential NullPointerException in the first code snippet above.

0 Answers
Related