Reputation: 67310
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.
Upvotes: 10
Views: 5791
Reputation: 1146
Right click on your current class >> analyze >> run inspection by name >> choose 'constant condition & exception' 'Java||Probable bugs'
Choose what you want to inspect and press ok.
In problems window, you will see suggestions offered by Intellij.
Upvotes: 0
Reputation: 17075
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.
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.
Upvotes: 5
Reputation: 4300
One way is to use Inspections.
Provided that the code is annotated by @Nullable
annotations you can use inspections:
And then choose Run Inspection by Name
:
Then you can choose the scope (Project, Tests, etc.)
Results will be shown in inspection tab:
You can find more on this in Nullable How-To
Upvotes: 2