Mfswiggs
Mfswiggs

Reputation: 347

Turning on Nullable warnings in Intellij

I am setting up my Intellij environment and I am wondering how to turn on Nullable warnings for the following:

Map<String, String> simpleMap = new HashMap<>();
String thisWillBeNull = simpleMap.get("key");
int l = thisWillBeNull.length();  //<-- how do I get a Nullable warning here?

Upvotes: 1

Views: 1005

Answers (4)

Jess
Jess

Reputation: 3745

I had the same question, so I asked a similar question in Intellij community

Here is the answer: https://youtrack.jetbrains.com/issue/IDEA-289285#focus=Comments-27-5802422.0-0

Solution

  1. add @Nullable to java.util.Map interface
  2. create a new Structural Search Inspection. However, it seems that you cannot share this config with your team by git directly.

enter image description here

Upvotes: 0

MRTJ
MRTJ

Reputation: 139

There is an option in Intellij:

Go to Analyze -> Inspect Code

This will analyze the code and point out possible issues in the code.

Upvotes: 0

mernst
mernst

Reputation: 8157

IntelliJ's nullity analysis is useful, but limited. It has weak handling for maps.

If you wish to obtain guarantees about code that uses maps, you could use the Nullness Checker, which includes a map key analysis. It isn't built into IntelliJ, but you can integrate it with IntelliJ or run it as a separate tool.

Given this code:

import java.util.HashMap;
import java.util.Map;

public class MapGetTest {
  void m() {
    Map<String, String> simpleMap = new HashMap<>();
    String thisWillBeNull = simpleMap.get("key");
    int l = thisWillBeNull.length();
  }
}

You can run this command:

javac -processor nullness MapGetTest.java

and the result is:

MapGetTest.java:8: error: [dereference.of.nullable] dereference of possibly-null reference thisWillBeNull
    int l = thisWillBeNull.length();
            ^
1 error

Upvotes: 1

Stephan Herrmann
Stephan Herrmann

Reputation: 8178

Generally, two things are needed to give tools a chance to detect the problem:

  • analysis must use null annotations to enable inter-procedural analysis
  • method Map.get() must be annotated to return @Nullable V. For library classes this may happen using external annotations.

Upvotes: 0

Related Questions