Java – is there a way for IntelliJ to warn me that this code may cause NullPointerException?

Is there any way for IntelliJ to warn me that this may lead to NullPointerException?

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

IntelliJ is very good at warning me of what I'm doing Is there any way to warn me of potential NPE here?

Note that there are no null / not null comments on getresources At least not what I'm using in JDK 1.7

Solution

IntelliJ's idea is to detect where @ nullable and @ notnull annotations apply and automatically insert them This can be done by

In this way, you can automatically add these comments to the current file, uncommitted files, or various other ranges

The disadvantage of this approach is that you must control the code being analyzed, so you cannot use it for third-party code Starting from IntelliJ idea 14, there is a function called automatic @ notnull / @ nullable / @ contract information By default, this function is active in IntelliJ idea 14 Idea analyzes the source code and automatically detects whether there should be @ nullable or @ notnull comments The key difference of invalid inference is that it does not actually insert algebra into the code itself, but only displays contract information on the left editor bar This is especially useful if you are using third-party libraries or do not want to use proprietary JetBrains annotations in your code

to update:

Note that the @ nullable annotation is no longer automatically inferred because it causes too many false positives https://youtrack.jetbrains.com/issue/IDEA-130063#comment=27 -812471

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

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>