'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?
Solution 1:[1]
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
Solution 2:[2]
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.
Solution 3:[3]
There is an option in Intellij:
Go to Analyze -> Inspect Code
This will analyze the code and point out possible issues in the code.
Solution 4:[4]
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
- add
@Nullabletojava.util.Mapinterface - create a new Structural Search Inspection. However, it seems that you cannot share this config with your team by git directly.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mernst |
| Solution 2 | Stephan Herrmann |
| Solution 3 | halfer |
| Solution 4 | kyakya |

