我希望使我的代码更具可读性,以及使用工具,如IDE代码检查和/或静态代码分析(FindBugs和Sonar),以避免nullpointerexception。许多工具似乎与彼此的@NotNull/@NonNull/ @NonNull注释不兼容,在我的代码中列出所有这些工具会让人难以阅读。有没有什么建议,哪一个是“最好的”?下面是我找到的等价注释列表:
javax.validation.constraints.NotNull
Created for runtime validation, not static analysis.
documentation
edu.umd.cs.findbugs.annotations.NonNull
Used by FindBugs (dead project) and its successor SpotBugs static analysis and therefore Sonar (now Sonarqube)
FindBugs documentation, SpotBugs documentation
javax.annotation.Nonnull
This might work with FindBugs too, but JSR-305 is inactive. (See also: What is the status of JSR 305?)
source
org.jetbrains.annotations.NotNull
Used by IntelliJ IDEA IDE for static analysis.
documentation
lombok.NonNull
Used to control code generation in Project Lombok.
Placeholder annotation since there is no standard.
source,
documentation
androidx.annotation.NonNull
Marker annotation available in Android, provided by annotation package
documentation
org.eclipse.jdt.annotation.NonNull
Used by Eclipse for static code analysis
documentation
One of the nice things about IntelliJ is that you don't need to use their annotations. You can write your own, or you can use those of whatever other tool you like. You're not even limited to a single type. If you're using two libraries that use different @NotNull annotations, you can tell IntelliJ to use both of them. To do this, go to "Configure Inspections", click on the "Constant Conditions & Exceptions" inspection, and hit the "Configure inspections" button. I use the Nullness Checker wherever I can, so I set up IntelliJ to use those annotations, but you can make it work with whatever other tool you want. (I have no opinion on the other tools because I've been using IntelliJ's inspections for years, and I love them.)
根据Java 7的特性列表,JSR-308类型注释被推迟到Java 8。甚至没有提到JSR-305注释。
在最新的JSR-308草案的附录中有一些关于JSR-305状态的信息。这包括观察到JSR-305注释似乎被抛弃了。JSR-305页面还将其显示为“inactive”。
同时,实用的答案是使用最广泛使用的工具所支持的注释类型……如果情况发生变化,也要做好改变的准备。
事实上,JSR-308没有定义任何注释类型/类,而且看起来他们认为这超出了范围。(考虑到JSR-305的存在,他们是正确的)。
然而,如果JSR-308真的想要加入Java 8,那么如果人们对JSR-305重新产生兴趣,我也不会感到惊讶。AFAIK, JSR-305团队还没有正式放弃他们的工作。他们已经沉默了2年多了。
有趣的是,Bill Pugh (JSR-305的技术主管)是FindBugs背后的人之一。