method invocation may produce NullPointerException is too aggressive in CE 14

This is with CE 14 (freshly built against

85b24a86
but it's been doing this for a while). Also, my apologies: I have tried very hard to reproduce this with self-contained code, but it's unclear what exactly is setting off the NPE warning.

In the following snippet, the
has()
protects the
get()
from returning
null
, although as IJ correctly determined, it could NPE if the subclass that
readTree()
returns doesn't override the
get()
from the abstract class
JsonNode
which is defined as
return null
.
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Main {
    public static void main(String[] args) throws Exception {
        JsonNode n = new ObjectMapper().readTree("{\"hello\": \"world\"}");
        if (n.has("hello")) {
            String s = n.get("hello").asText();
//-----------------------------------^^^^^^^^^
// warns that the asText could produce NPE
        }
    }
}


So I understand that conclusion, and thus am willing to compromise with the inference engine and cast the result to the concrete subclass that I know it is:

String s = ((TextNode)n.get("hello")).asText();
//-----------^^^^^^^^
// redundant cast


However, now I get a different warning, in that the cast is redundant because I am not invoking a method that requires the downcast to access.
I would prefer not to litter the code with

assert thing != null
, nor the inspection suppression
//noinspection ConstantConditions
.

I almost filed a YouTrack for this, but I realized I can't quite articulate what the bug is; I can't expect IJ to know every API in the world, nor would I necessarily want to switch off the redundant cast inspection.

What is the correct behavior here, either on my part or on IJ's part?

Please sign in to leave a comment.