Is there a way to get Intellij to warn me that this code could throw a NullPointerException?

Is there a way to get Intellij to warn me that this might throw a NullPointerException?

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

Intellij warns me perfectly about the stupid things I do. Is there a way to warn me of potential NPE here?

Keep in mind that getResources does not contain any null / notnull annotations on it . At least not in the JDK 1.7 that I use.

+7
java nullpointerexception intellij-idea
source share
2 answers

The idea of ​​Intellij can determine where @Nullable and @NotNull annotations fit, and automatically insert them . This can be done using

Analysis β†’ Infer Nullity

Thus, you can automatically add these annotations to the current file, to files with unlimited access, or to other areas.

The disadvantage of this approach is that you have to control the code that 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 Output . By default, this function is included in intellij idea 14. The idea analyzes the source code and automatically determines whether there should be an @Nullable or @NotNull annotation. The main difference from infer nullity is that it does not actually insert the annotation into the code itself, but only displays information about the contract in the left pane of the editor. This is especially good if you work with third-party libraries or don’t want your code to contain annotations of your own reactive brains.

Auto-inferred @NotNull annotations

UPDATE:

Please note that the @Nullable annotation is no longer automatically displayed, as a result of too many false positives https://youtrack.jetbrains.com/issue/IDEA-130063#comment=27-812471

In addition, according to a comment from Peter Gromov for this author mentioned above , not all methods are deduced by this function

Also note that contracts are not inferred for methods that can be overridden, that is, non-static non-private non-final methods dont have contracts.

+4
source share

IntelliJ IDEA Inspections

One way is to use Inspections .

Provided that the code is annotated with @Nullable annotations, you can use checks:

Analyze menu

And then select Run Inspection by Name :

@Nullable problems

Then you can select the scope (project, tests, etc.).

enter image description here

The results will be shown on the inspection tab:

enter image description here

Nullable how-to

Learn more about this in Nullable How-To.

+2
source share

All Articles