Reputation: 347
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
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
@Nullable
to java.util.Map
interfaceUpvotes: 0
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
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
Reputation: 8178
Generally, two things are needed to give tools a chance to detect the problem:
Map.get()
must be annotated to return @Nullable V
. For library classes this may happen using external annotations.Upvotes: 0