我希望使我的代码更具可读性,以及使用工具,如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
这里已经有太多答案了,但是(a)现在是2019年,仍然没有“标准”Nullable, (b)没有其他答案引用Kotlin。
引用Kotlin是很重要的,因为Kotlin与Java是100%可互操作的,并且它有一个核心的Null安全特性。在调用Java库时,它可以利用这些注释让Kotlin工具知道Java API是否可以接受或返回null。
据我所知,唯一与Kotlin兼容的Nullable包是org.jetbrains.annotations和android.support.annotation(现在是androidx.annotation)。后者只与Android兼容,所以不能在非Android的JVM/Java/Kotlin项目中使用。然而,JetBrains包在任何地方都可以工作。
因此,如果您开发的Java包也应该在Android和Kotlin上工作(并且得到Android Studio和IntelliJ的支持),那么最好的选择可能是JetBrains包。
Maven:
<dependency>
<groupId>org.jetbrains</groupId>
<artifactId>annotations-java5</artifactId>
<version>15.0</version>
</dependency>
Gradle:
implementation 'org.jetbrains:annotations-java5:15.0'
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.)