Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get Intellij to warn me that this code may cause a NullPointerException?

Is there a way to get Intellij to warn me that this may cause a NullPointerException?

URL resource = Main.class.getResource("blah/ha");
System.out.println(resource.getAuthority());  //potential NPE here

Intellij is great at warning me about stupid things I'm doing. Is there a way it can warn me about the potential NPE here?

Please be aware that getResources does not have any of those null/notnull annotations on it. At least not in JDK 1.7 which is what I'm using.

like image 888
Daniel Kaplan Avatar asked Mar 05 '15 02:03

Daniel Kaplan


2 Answers

Intellij idea can detect where @Nullable and @NotNull annotations are appropriate and automatically insert them. This can be done with

Analyze -> Infer Nullity

This way you can automatically add these annotations to current file, uncommited files or various other scopes.

Disadvantage of this approach is that you have to have control over the code you are analyzing, so you cannot use it for third party code. Starting with Intellij Idea 14, there is a feature called Automatic @NotNull/@Nullable/@Contract inference. This feature is active in intellij idea 14 by default. Idea analyzes the source code and automatically detects whether there should be @Nullable or @NotNull annotation. The key difference from infer nullity is that it actually does not insert the anotation to the code itself, but only displays contract information on the left editor bar. This is especially good if you are working with third party libraries or do not want proprietary jetbrains annotations in your code.

Auto-inferred @NotNull annotations

UPDATE:

Note that @Nullable annotation is no longer automatically inferred asit resulted in too many false positives https://youtrack.jetbrains.com/issue/IDEA-130063#comment=27-812471

Also, according a comment by Peter Gromov for this author of the post mentioned above, not all methods are inferred by this feature

Please also note that contracts are not inferred for methods that can be overridden, i.e. non-static non-private non-final methods don’t have contracts.

like image 150
Vojtech Ruzicka Avatar answered Nov 06 '22 00:11

Vojtech Ruzicka


IntelliJ IDEA Inspections

One way is to use Inspections.

Provided that the code is annotated by @Nullable annotations you can use inspections:

Analyze menu

And then choose Run Inspection by Name:

@Nullable problems

Then you can choose the scope (Project, Tests, etc.)

enter image description here

Results will be shown in inspection tab:

enter image description here

Nullable How-To

You can find more on this in Nullable How-To

like image 2
Nader Ghanbari Avatar answered Nov 06 '22 01:11

Nader Ghanbari